从DataGridView创建Excel文件
我在WindowsForms中有一个DataGridView。我想要一个按钮将此数据杂志导出到Excel工作表。
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application ExcelApp;
Excel.Workbook ExcelWorkBook;
Excel.Worksheet ExcelWorkSheet;
ExcelApp = new Excel.Application();
ExcelWorkBook = ExcelApp.Workbooks.Add(Missing.Value);
ExcelWorkSheet = (Excel.Worksheet)ExcelWorkBook.Worksheets.get_Item(1);
try
{
for (int i = 0; i <= dataGridView1.RowCount - 1; ++i)
{
for (int j = 0; j <= dataGridView1.ColumnCount - 1; ++j)
{
DataGridViewCell cell = dataGridView1[j, i];
ExcelWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}
} catch (Exception ex) { /*somestuff*/ }
// save ExcelWorkbook
此代码有效。但不幸的是,时间复杂性很差。因此,我被迫实施进度栏。如果我不这样做,则用户会在导出大型DataGridView时认为该程序崩溃了。不用说,这当然会减慢出口的速度。 (在此问题中不包含进度键代码)
我想知道,是否有一种将数据杂志导出到Excel更快的方法。
I have a dataGridView in a WindowsForms. I want a button to export this dataGridView to an Excel Worksheet.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application ExcelApp;
Excel.Workbook ExcelWorkBook;
Excel.Worksheet ExcelWorkSheet;
ExcelApp = new Excel.Application();
ExcelWorkBook = ExcelApp.Workbooks.Add(Missing.Value);
ExcelWorkSheet = (Excel.Worksheet)ExcelWorkBook.Worksheets.get_Item(1);
try
{
for (int i = 0; i <= dataGridView1.RowCount - 1; ++i)
{
for (int j = 0; j <= dataGridView1.ColumnCount - 1; ++j)
{
DataGridViewCell cell = dataGridView1[j, i];
ExcelWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}
} catch (Exception ex) { /*somestuff*/ }
// save ExcelWorkbook
This code works. But unfortunately the time complexity is bad. So I'm forced to implement a progressbar. If i wouldn't do it, the user would be thinking the program crashed, while exporting a big datagridview. Needless to say, this will of course slow down the export even more. (progressbar code is not included in this question)
I wonder, if there is a method to export a datagrid to an excel faster.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您提示使用另一个第三方库。
我给Epplus一个机会。
这是代码:
就像地狱一样快。缺点是:它的记忆饿了。
Thanks for the hints to use another third-party library.
I was giving EPPLus a chance.
Here is the code:
It's fast like hell. The drawback is: It's memory hungry.