【发布时间】:2017-01-18 16:02:33
【问题描述】:
我确实有一个按钮单击事件上的 c# 窗口应用程序,它使用 Microsoft Office 互操作 Excel 模块将 datagridview 导出到 Excel。
但我发现用于导出数据的时间很慢,我发现其他人正在使用 2D Array 方法来加快它。我确实尝试过,但我无法正确过滤掉它。
我之前确实尝试过手动关闭 Excel 计算,但它仍然没有帮助。对此有何建议?
这是我的代码:
//Create Excel Object.
Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = objexcelapp.Application.Workbooks.Add(Type.Missing);
//objexcelapp.Columns.ColumnWidth = 30;
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "Daily Report";
worksheet.Range["A1", "S1"].Interior.Color = Excel.XlRgbColor.rgbBurlyWood;
for (int i = 1; i < dailyReportGridView.Columns.Count + 1; i++)
{
if (i != 20 && i != 21 && i != 22)
{
objexcelapp.Cells[1, i] = dailyReportGridView.Columns[i - 1].HeaderText;
}
}
/*For storing Each row and column value to excel sheet*/
for (int i = 0; i < dailyReportGridView.Rows.Count; i++)
{
for (int j = 0; j < dailyReportGridView.Columns.Count; j++)
{
if (dailyReportGridView.Rows[i].Cells[j].Value != null && j != 19 && j != 20 && j != 21 && j != 22)
{
objexcelapp.Cells[i + 2, j + 1] = dailyReportGridView.Rows[i].Cells[j].Value.ToString();
AllBorders(objexcelapp.Cells[i + 2, j + 1].Borders);
}
}
}
objexcelapp.Columns.AutoFit(); //Auto fit all the data length to the column by Marcus 10-09-2016
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && dailyReportGridView.RowCount > 1)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Excel File Had Been Saved!", "Success");
}
else
{
MessageBox.Show("Operation Canceled.", "Failed To Save");
}
}
catch (Exception ex)
{
MessageBox.Show("Export Excel Error" + ex.Message);
}
finally
{
objexcelapp.Quit();
workbook = null;
objexcelapp = null;
}
【问题讨论】: