WPF 应用程序将数据表写入 Excel 的更有效方法?

2024-02-21

In my WPF应用程序,我有一个巨大的数据表(System.Data.DataTable)我需要写入 Excel 文档中的工作表。这是该函数的重点部分:

for (; i < dt.Rows.Count; i++)
{
    for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
        newSheet.Cells[i + rowNumber, colNum + 1] = dt.Rows[i][colNum].ToString();

    applyRowBorderStyle(newSheet, i + rowNumber, dt.Columns.Count);
}

dt 是DataTable, newSheet是我写入的 Excel 工作表,并且applyRowBorderStyle()为行中的所有单元格添加边框。当数据表很大时,运行速度非常慢,需要10分钟甚至更长时间。有什么办法让它跑得更快吗?


编辑:该程序分析大量数据并制作大量表格,我无法让用户做任何不同的事情。我只能使用 Microsoft Excel。该工作表的表格始终有 42 列,但行数根据程序接收的数据量而变化,大约为 500 行。 “applyRowBorderStyle”会使代码运行得更快一点,但不满足要求。我真的希望有另一种方法可以让它运行得更快。


找到答案了!这是 iv'e 编写的函数以及我使用的参考:http://www.codeproject.com/Articles/21519/Fast-Exporting-from-DataSet-to-Excel http://www.codeproject.com/Articles/21519/Fast-Exporting-from-DataSet-to-Excel

using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

private void FastDtToExcel(DataTable dt, Excel.Worksheet sheet, int firstRow, int firstCol, int lastRow, int lastCol)
{
    Excel.Range top = sheet.Cells[firstRow, firstCol];
    Excel.Range bottom = sheet.Cells[lastRow, lastCol];
    Excel.Range all = (Range)sheet.get_Range(top, bottom);
    string[,] arrayDT = new string[dt.Rows.Count, dt.Columns.Count];

    //loop rows and columns
    for (int i = 0; i < dt.Rows.Count; i++)
        for (int j = 0; j < dt.Columns.Count; j++)
            arrayDT[i, j] = dt.Rows[i][j].ToString();

    //insert value in worksheet
    all.Value2 = arrayDT;
}

花费不到一秒钟,这太棒了:)

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

WPF 应用程序将数据表写入 Excel 的更有效方法? 的相关文章

随机推荐