我需要將DataGridView的內容保存到Excel中,並且能夠將DataGridView的單元格中的單元格顏色與Excel中的單元格進行匹配。C#Winforms格式保存爲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);
}
}
http://stackoverflow.com/questions/3989122/microsoft-office-interop-excel-really-slow看到 –
你可以如EPPlus嘗試使用第三方庫(Excel中2007+)或Aspose。或者嘗試分析你的Interop代碼來理解爲什麼它「如此如此之慢」。可能有些事情可以改善表現,例如請參閱http://stackoverflow.com/questions/3989122/microsoft-office-interop-excel-really-slow/3989452#3989452 – Joe
由於互操作性,此方法相當慢。您可以使用第三方工具,例如Flexcel Spreadsheet或Gembox Spreadsheet,也提供樣式和格式。 –