Microsoft.Office.Interop.Excel really slow

前端 未结 8 1605
执笔经年
执笔经年 2020-11-27 13:43

I am exporting a 1200 X 800 matrix (indexMatrix) to a excel file using the standard Microsoft.Office.Interop.Excel. The app works, just that it is really really really slow(

8条回答
  •  死守一世寂寞
    2020-11-27 14:28

    I am answering a little bit late sorry. I was working on my project and we had to use interop excel. And our data was too big, which was taking more than 1 minute with interop excel. We tried something else which is copy the all content of datagridview to clipboard, open an excel worksheet using interop excel, and paste the content to excel. It takes less than 1 second and exports our data perfectly.

    DataGridView to string:

        var newline = System.Environment.NewLine;
        var tab = "\t";
        var clipboard_string = "";
    
        foreach (DataGridViewRow row in dgProjeler.Rows)
        {
            for (int i = 0; i < row.Cells.Count; i++)
            {
                if (i == (row.Cells.Count - 1))
                    clipboard_string += row.Cells[i].Value + newline;
                else
                    clipboard_string += row.Cells[i].Value + tab;
            }
        }
    

    and copy the string to clipboard

            Clipboard.SetText(clipboard_string);
    

    And open a worksheet, paste the content.

            Excel.Application app = new Excel.Application();
            app.Visible = true;
            Excel.Workbook wb = app.Workbooks.Add(1);
            Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
            // changing the name of active sheet
            ws.Name = "Exported from gridview";
    
            ws.Rows.HorizontalAlignment = HorizontalAlignment.Center;
            app.ActiveWindow.Activate();
    
    
            ws.Activate();
            ws.Paste();
    
            ws.Cells.EntireColumn.AutoFit();
    

    It works perfectly on me, I hope it helps people who still couldn't find the solution.

提交回复
热议问题