Export from DataGrid to Excel with Interop is too slow

只谈情不闲聊 提交于 2019-12-02 01:43:50

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