【发布时间】:2014-04-08 22:04:20
【问题描述】:
我需要将 DataGridView 的内容保存到 Excel,并且能够将 DataGridView 的单元格中的单元格颜色与 Excel 中的单元格匹配。
如果我要保存到 CSV,文件的保存是即时的,但不能应用任何样式,所以我需要使用 Microsoft.Office.Interop.Excel
这给了我正确的样式,但它是如此如此如此缓慢。
有解决办法吗?
public static void ExportToExcel(this DataGridView Tbl, string ExcelFilePath = null)
{
try
{
if (Tbl == null || Tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].Name;
}
// rows
for (int i = 0; i < Tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < Tbl.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i].Cells[j].Value;
((Excel.Range)(workSheet.Cells[(i + 2), (j + 1)])).Interior.Color = System.Drawing.Color.Orange;//System.Drawing.ColorTranslator.ToOle(Tbl.Rows[i].Cells[j].Style.BackColor);
//workSheet.Cells[(i + 2), (j + 1)].Interior.Color = Tbl.Rows[i].Cells[j].Style.BackColor;
}
}
// check filepath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
【问题讨论】:
-
您可以尝试使用第三方库,例如 EPPlus (Excel 2007+) 或 Aspose。或者尝试分析您的互操作代码以了解它为什么“这么慢”。您可能可以做一些事情来提高性能,例如见stackoverflow.com/questions/3989122/…
-
由于互操作性,这种方法相当慢。您可以使用第三方工具,如 Flexcel 电子表格或 Gembox 电子表格,它们也提供样式和格式。
-
我可以以同样的方式将上面的矩阵示例与 DataTable 一起使用吗?
-
似乎将 DataTable 或 DataGridView 传递到这一行
range.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, indexMatrix);会导致错误。应该传入什么类型?
标签: c# winforms excel datagridview