返回首页
当前位置: 主页 > 网络编程 > .Net实例教程 >

实现.net操作Excel程序代码

时间:2011-05-24 14:12来源:知行网www.zhixing123.cn 编辑:麦田守望者

#region 将DataTable中的数据读取到Excel中,返回bool值
/// <summary>
/// 将DataTable中的数据读取到Excel中,返回bool值
/// </summary>
/// <param name="DataSource">进行处理的datatable</param>
/// <returns></returns>
public static bool DataTableToExc(System.Data.DataTable DataSource)
{
try
{
if (DataSource.Rows.Count == 0)
return false;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);

//生成字段名称
for (int i = 0; i < DataSource.Columns.Count; i++)
{
excel.Cells[1, i + 1] = DataSource.Columns[i].ColumnName;
}
//填充数据
for (int i = 0; i < DataSource.Rows.Count - 1; i++)
{
for (int j = 0; j < DataSource.Columns.Count; j++)
{
excel.Cells[i + 2, j + 1] = DataSource.Rows[i][j].ToString();
}
}
excel.Visible = true;
return true;
}
catch (Exception ex)
{
exceptionMessage = ex.Message;
return false;
}
}
#endregion
示例2
{//保存为Excel文件
if(this.listView1.Items.Count<1)
return;
try
{
Microsoft.Office.Interop.Excel.ApplicationClass myExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
myExcel.Visible = true
if(myExcel==null)
{
MessageBox.Show("Excel无法启动!!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
Microsoft.Office.Interop.Excel.Workbooks myWorkBooks = myExcel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook myWorkBook = myWorkBooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet myWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)myWorkBook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range myRange = myWorkSheet.get_Range("A1","C1");
object[] myHeader = {"姓名","专业","毕业院校"};
myRange.Value2 = myHeader;
if(this.listView1.Items.Count>0)
{
myRange = myWorkSheet.get_Range("A2",System.Reflection.Missing.Value);
object[,] MyData = new object[this.listView1.Items.Count,3];
foreach(ListViewItem lvi in this.listView1.Items)
{
MyData[lvi.Index,0] = lvi.Text;
MyData[lvi.Index,1] = lvi.SubItems[1].Text;
MyData[lvi.Index,2] = lvi.SubItems[2].Text
}
myRange = myRange.get_Resize(this.listView1.Items.Count,3);
myRange.Value2 = MyData;
myRange.EntireColumn.AutoFit();
}
myExcel = null;
}
catch(System.Exception ex)
{
MessageBox.Show(this,ex.Message.ToString(),"信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information)
}
}

------分隔线----------------------------
标签(Tag):C# C#实例教程 c#基础教程 C#源代码
------分隔线----------------------------
推荐内容
猜你感兴趣