How to optimize exporting data to excel in Excel Interop?

北慕城南 提交于 2019-12-11 09:34:54

问题


I am using Excel interop to create excel workbooks from my query results. When there are thousands of records it takes a long time for the workbook to be generated. The below code is a sample of how I am populating the cells.

RowNo = 1
For i = 1 To 4000
   ColNo = 1
   For j = 1 To 5
      Dim cell As excel.Range = ws.Cells(RowNo, ColNo)
      Dim value = j
      cell.Value = value
      ColNo = ColNo + 1
   Next
   RowNo = RowNo + 1
Next

For the above code to run it takes more than a minute. How can I optimize it?


回答1:


Found the answer. You can write data to an array and then write the array to the excel range rather than writing the data cell by cell. See http://www.clear-lines.com/blog/post/Write-data-to-an-Excel-worksheet-with-C-fast.aspx

private static void WriteArray(int rows, int columns, Worksheet worksheet)
{
    var data = new object[rows, columns];
    for (var row = 1; row <= rows; row++)
    {
        for (var column = 1; column <= columns; column++)
        {
            data[row - 1, column - 1] = "Test";
        }
    }

    var startCell = (Range)worksheet.Cells[1, 1];
    var endCell = (Range)worksheet.Cells[rows, columns];
    var writeRange = worksheet.Range[startCell, endCell];

    writeRange.Value2 = data;
}


来源:https://stackoverflow.com/questions/12743077/how-to-optimize-exporting-data-to-excel-in-excel-interop

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