Export from DataGrid to Excel with Interop is too slow

萝らか妹 提交于 2019-12-04 04:56:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!