1

我正在使用 Excel 互操作从我的查询结果中创建 Excel 工作簿。当有数千条记录时,生成工作簿需要很长时间。下面的代码是我如何填充单元格的示例。

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

上面的代码运行需要一分钟多的时间。我该如何优化它?

4

1 回答 1

1

找到了答案。您可以将数据写入数组,然后将数组写入 excel 范围,而不是逐个单元格地写入数据。请参阅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;
}
于 2012-10-05T12:48:16.037 回答