Microsoft.Office.Interop.Excel 真的很慢

2023-12-01

我正在使用标准 Microsoft.Office.Interop.Excel 将 1200 X 800 矩阵 (indexMatrix) 导出到 excel 文件。该应用程序可以工作,只是它真的非常非常慢(即使对于 100 x 100 矩阵)。我还通过 TextWriter 导出文本文件,它几乎可以立即运行。有什么办法可以更快的导出到excel文件吗?

这是我的代码:

        Excel.Application xlApp=new Excel.Application();
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        //xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        for (int i = 0; i < 800; i++)   //h
            for (int j = 0; j < 1200; j++)
                xlWorkSheet.Cells[i+1,j+1] =indexMatrix[i][j];


        xlWorkBook.SaveAs("C:\\a.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");

您正在更新单个单元格。那会非常慢。如果您考虑一下,每次更新单元格时,都会将 RPC 调用编组到 Excel 进程。

这将是much如果您在单个语句(一次跨进程调用)中将二维值数组分配给相同维度的 Excel Range,而不是当前的 1200 x 800 = 960,000 跨进程调用,速度会更快。

就像是:

// Get dimensions of the 2-d array
int rowCount = indexMatrix.GetLength(0);
int columnCount = indexMatrix.GetLength(1);
// Get an Excel Range of the same dimensions
Excel.Range range = (Excel.Range) xlWorkSheet.Cells[1,1];
range = range.get_Resize(rowCount, columnCount);
// Assign the 2-d array to the Excel Range
range.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, indexMatrix);

实际上,为了迂腐,上面的代码中有三个跨进程调用(.Cells、.get_Resize 和 .set_Value),并且代码中每次迭代有两个调用(.Cells get 和隐式 .set_Value)总计 1200 x 800 x 2 = 1,920,000。

Note range.get_Resize and range.set_Value当我第一次撰写这篇文章时,我正在使用旧版本的 Excel 互操作库。这几天你可以使用range.Resize and range.Value正如@The1nk 的评论中所述。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Microsoft.Office.Interop.Excel 真的很慢 的相关文章

随机推荐