我在c#中有一个datagridview,我正在显示记录。现在根据我的要求我必须将它导出到excel.So我已经为此写了以下方法..
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
object misValue = System.Reflection.Missing.Value;
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, misValue, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue);
currentWorkbook.Saved = true;
MessageBox.Show("Exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
现在有一件奇怪的事情正在发生,当我试图使用我的应用程序获取excel报告我无法得到它而如果我试图通过调试我的代码得到它我得到但它也是地狱很多时间 在调试代码这一行..
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
花了很多时间..
请帮帮我..
答案 0 :(得分:0)
Excel Interop
永远不会快,因为您正在远程控制Excel应用程序的实例。您可能需要创建一个CSV文件,然后使用Excel Interop
将其转换为.xls
或.xlsx
文件。
以下是关于如何将csv转换为xls
的示例using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workBook = excel.Workbooks.Add();
var inputFile = new FileInfo("Book1.csv");
var sheet = Spreadsheet.Read(inputFile);
workBook.ActiveSheet = sheet; // unsure about this part, but basically you need to transfer data.
workBook.SaveAs(@"C:\Temp\fromCsv.xls");
workBook.Close();
答案 1 :(得分:0)
我认为以下部分会大大减慢您的代码
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
我认为通过不每次循环调用DataGridView
,将Cells
导出到Excel电子表格会快得多,因为每次调用Cells
都是使用COM时非常昂贵。
我建议您将DataGridViewColumn
转换为2D数组,然后像这样一次导出整个DataGridView
:
object[,] toExport = new object[dgView.Rows.Count, dgView.Columns.Count];
for (int row = 0; row < dgView.Rows.Count; row++)
{
DataGridViewRow dgRow = dgView.Rows[row];
for (int column= 0; column < dgRow.Cells.Count; column++)
{
toExport[row, column] = dgRow.Cells[row].Value;
}
}
// export in one go instead of looping and accessing Cells each time
// use Excel.Application.Transpose(array) if needed
ws.get_Range("A3").set_Value(Type.Missing, toExport);
此外,您可以在开始时添加xlApp.ScreenUpdating = false;
,然后在完成修改工作表后将其切换回true
。