问题
I'm about to write a WPF application that takes data from database and displays it in DataGrid. Then with a button an Excel file is created and filled with the data. With large quantities like 20000 lines the filling in Excel takes too long. Does someone have an idea why? Thank you
private void copyAlltoClipboard()
{
Clipboard.Clear();
DataGrid1.SelectAllCells();
DataGrid1.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, DataGrid1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
copyAlltoClipboard();
Excel.Application xlexcel;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
回答1:
This is the method that I am using currently.
But this is much similar to your code. But I am using a data object to copy the content to clipboard. This works really fine for me. But a number of lines like 20000 will anyway affect the performances.
private void btnExportToExcel_Click(object sender, EventArgs e)
{
copyDataGridToClipboard();
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
private void copyDataGridToClipboard()
{
YourDataGridView.MultiSelect = true;
yourDataGridView.SelectAll();
DataObject dataObj = yourDataGridView.GetClipboardContent();
if (dataObj != null)
{
Clipboard.SetDataObject(dataObj);
}
yourDataGridView.MultiSelect = true;
}
来源:https://stackoverflow.com/questions/52832292/export-from-datagrid-to-excel-with-interop-is-too-slow