我将要编写一个WPF应用程序,该应用程序将从数据库中获取数据并将其显示在DataGrid中。然后用一个按钮创建一个Excel文件并用数据填充。对于20000行这样的大量数据,Excel中的填充时间太长。有人知道为什么吗?谢谢
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);
}
答案 0 :(得分:0)
这是我目前正在使用的方法。
但这与您的代码非常相似。但是我正在使用数据对象将内容复制到剪贴板。这对我来说真的很好。但是无论如何,许多行(例如20000)都会影响性能。
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;
}