刑天的歌 » 日志 » 将DataSet中的数据写入Excel(C#)
将DataSet中的数据写入Excel(C#)
刑天 发表于 2006-07-24 22:23:53
有这样的任务,通过ADO.NET从数据库读取数据到DataSet,数据绑定到DataGrid或者.NET2.0里的新控件DataGridView,最后将数据写入Excel文件,提供给用户进一步的分析,如打印、图表等。程序最终运行如下:




前面的步骤都很简单,关键是写Excel,毕竟Excel不是数据格式,在C#中调用Excel表格要使用到Excel的COM组件。如果你装的Office2000 ,在"C:\Program Files\Microsoft Office\Office"可以找到这个COM组件"EXCEL9.OLB",这些COM组件都是非受管代码的,要在C#中使用这些非受管代码的COM组件,就必须把他们转换成受管代码的类库。所以在用C#调用Excel表格之前,必须完成从COM组件的非受管代码到受管代码的类库的转换。在DOS命令行下键入:
tlbimp excel9.olb
这样在excel9.olb目录下就产生了三个DLL文件:"Excel.dll"、"Office.dll"、"VBIDE.dll"。
但Office2000以后的版本没有*.olb文件,对2003可以直接到OFFICE安装目录,利用.net 中带的工具在命令提示符下执行:
tlbimp excel.exe
还是会生成Excel.dll,在工程中引用这个文件就可以了。


这样与Excel有关的类都加了进来,别忘了在namespace里添加using Excel。
窗体上添加一个按钮,对Click事件方法如下:
private void button1_Click(object sender, EventArgs e)
{
int count = this.archiverdbDataSet.channel.Rows.Count;//获取数据表中DataRow行总数
int column = this.archiverdbDataSet.channel.Columns.Count;//获取数据表中列总数
Excel.ApplicationClass excelapp = new ApplicationClass();
//Make Excel Application Visible
excelapp.Visible = true;
//写入特定文件
//Excel.Workbook wb = excelapp.Workbooks.Open(string filename,
// Type.Missing,Type.Missing,Type.Missing,Type.Missing,
// Type.Missing,Type.Missing,Type.Missing,Type.Missing,
// Type.Missing,Type.Missing,Type.Missing,Type.Missing,
// Type.Missing,Type.Missing);
Excel.Workbook wb = excelapp.Application.Workbooks.Add(true);
for (int x = 1; x <= count; x++)
{
for (int y = 1; y <= column; y++)
{
excelapp.Cells[x, y] = this.archiverdbDataSet.channel.Rows[x- 1].ItemArray[y - 1];
}
}
string tname = "C:\Book2.xls";
wb.SaveAs(tname, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
try
{
wb.Saved = true;
excelapp.UserControl = false;
//excelapp.Quit();
}
catch(System.Exception op)
{
MessageBox.Show("wrong" + op.Message);
}
}
以上在VS.net 2005里测试通过。当然你还可以把Excel做的漂亮点,参考文档有例子,不过没试过。
参考文档:
相关日志:
- » 纪念zc姐姐
- » 魔力宝贝物品管理器C#版新鲜出炉~
- » 这个有用
- » C#中Interface的说明【转】
- » override 委托
收藏:
QQ书签
del.icio.us
订阅:
Google
抓虾
最新评论
-
2006-07-25 10:36:10 http://blog.sina.com.cn/u/1242304073
不错,小样有前途
-
2006-07-31 15:41:29 http://blog.sina.com.cn/u/1242304073
小样,真的回家了还?
我也要闪回老婆家去几天,休息一下了
