积极答复者
winform下datagridview导出到excel文件的办法,什么比较可靠好用

问题
答案
-
使用流的方式实际上就是生成一文本文件,每个字段以 tab 分隔。优点:不依赖 Office, 速度快。缺点:不能为生成的 Excel 设置样式,比如字体背景等。使用 Office 的 Excel.Application,速度稍慢,支持所有的 Excel 操作。上面的例子有个问题,它是每一个单元格赋一次值,在导出大量数据量时效率低。我前段时间写了个示例解决了这个问题,请参考下面的地址:
知识改变命运,奋斗成就人生!- 已标记为答案 ahking 2009年11月5日 7:58
-
如果你使用方法1和3,你需要正确的清理掉Excel对象。我个人认为方法2很好,不需调用Excel程序,性能上好。
Best regards,
Riquel
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- 已标记为答案 ahking 2009年11月5日 7:58
全部回复
-
有好几种方法,有个比较不同的方法是用流的方法,不知哪种更好些
http://www.yongfa365.com/Item/DataGridViewToExcel.html -
使用流的方式实际上就是生成一文本文件,每个字段以 tab 分隔。优点:不依赖 Office, 速度快。缺点:不能为生成的 Excel 设置样式,比如字体背景等。使用 Office 的 Excel.Application,速度稍慢,支持所有的 Excel 操作。上面的例子有个问题,它是每一个单元格赋一次值,在导出大量数据量时效率低。我前段时间写了个示例解决了这个问题,请参考下面的地址:
知识改变命运,奋斗成就人生!- 已标记为答案 ahking 2009年11月5日 7:58
-
try
{
Excel.Application xlApp = new Excel.ApplicationClass();int rowIndex=0;
int colIndex=0;Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
foreach (DataGridViewColumn colu in grid.Columns)
{
xlApp.Cells[0, colIndex] = colu.HeaderText;
colIndex = colIndex + 1;
}//得到的表所有行,赋值给单元格
for (int row = 0; row < grid.Rows.Count; row++)
{
rowIndex = rowIndex + 1;
colIndex = 0;
for (int col = 0; col < grid.Columns.Count; col++)
{
if (grid.Columns[col].CellType.Name == "DataGridViewComboBoxCell")
{
xlApp.Cells[rowIndex, colIndex] = grid.Rows[row].Cells[col].FormattedValue;
}
else
{
xlApp.Cells[rowIndex, colIndex] = grid.Rows[row].Cells[col].Value;
}
colIndex = colIndex + 1;
}
}
xlApp.Visible = true;
//保存
xlBook.Saved = true;
xlBook.SaveCopyAs(fileName);}
catch (Exception e)
{
throw e;
}
finally
{
GC.Collect(); //强制回收
}
根据网上的一个方法添加引用:
1. 在visual Studio 2005命令提示工具中,定位到Excel安装目录,运行“TlbImp EXCEL.EXE”命令,把Excel.exe编译为Excel.dll,
2. 引用刚编译好的Excel.dll,添加引用using Excel;删除Microsoft.Office.Interop.Excel;
用Excel替换Microsoft.Office.Interop.Excel。
这是我写的一个方法,在调用时出错
System.IO.FileNotFoundException: 未能加载文件或程序集“Excel, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。系统找不到指定的文件。
文件名:“Excel, Version=1.5.0.0, Culture=neutral, PublicKeyToken=null”
当我把excel文件拷到程序目录时出以下错误:
System.Runtime.InteropServices.COMException (0x800A03EC): 异常来自 HRESULT:0x800A03EC
请问是怎么回事,而且我也不想运行程序时带着excel -
使用流的方式实际上就是生成一文本文件,每个字段以 tab 分隔。
关于引用的问题:优点:不依赖 Office, 速度快。缺点:不能为生成的 Excel 设置样式,比如字体背景等。使用 Office 的 Excel.Application,速度稍慢,支持所有的 Excel 操作。上面的例子有个问题,它是每一个单元格赋一次值,在导出大量数据量时效率低。我前段时间写了个示例解决了这个问题,请参考下面的地址:
知识改变命运,奋斗成就人生!
添加了com中office object...11 引用,结果只有office.core的命名空间,然后按下述的办法又报错。 -
如果你使用方法1和3,你需要正确的清理掉Excel对象。我个人认为方法2很好,不需调用Excel程序,性能上好。
Best regards,
Riquel
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- 已标记为答案 ahking 2009年11月5日 7:58