且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#Microsoft.Office.Interop.Excel导出

更新时间:2023-02-08 09:42:48

我刚刚遇到了同样的性能问题,并将其写到了基准测试中:

I just took the same performance hit, wrote this to benchmark:

[Test]
public void WriteSpeedTest()
{
    var excelApp = new Application();
    var workbook = excelApp.Workbooks.Add();
    var sheet = (Worksheet)workbook.Worksheets[1];
    int n = 1000;
    var stopwatch = Stopwatch.StartNew();
    SeparateWrites(sheet, n);
    Console.WriteLine("SeparateWrites(sheet, " + n + "); took: " + stopwatch.ElapsedMilliseconds + " ms");

    stopwatch.Restart();
    BatchWrite(sheet, n);
    Console.WriteLine("BatchWrite(sheet, " + n + "); took: " + stopwatch.ElapsedMilliseconds + " ms");

    workbook.SaveAs(Path.Combine(@"C:\TEMP", "Test"));
    workbook.Close(false);
    Marshal.FinalReleaseComObject(excelApp);
}

private static void BatchWrite(Worksheet sheet, int n)
{
    string[,] strings = new string[n, 1];
    var array = Enumerable.Range(1, n).ToArray();
    for (var index = 0; index < array.Length; index++)
    {
        strings[index, 0] = array[index].ToString();
    }

    sheet.Range["B1", "B" + n].set_Value(null, strings);
}

private static void SeparateWrites(Worksheet sheet, int n)
{
    for (int i = 1; i <= n; i++)
    {
        sheet.Cells[i, 1].Value = i.ToString();
    }
}

结果:

                            n = 100   n = 1 000   n = 10 000    
SeparateWrites(sheet, n);   180 ms    1125 ms     10972 ms
BatchWrite(sheet, n);       3 ms      4 ms        14 ms