使用 c# 将大型 SQL 服务器结果导出到 excel(行数 = 100 万)

Export a large SQL Server result to excel (Row Count = 1 Million) using c#

我需要将 SQL 服务器结果导出到 excel 文件(至少一百万行和最少 50 列)

限制条件:

  1. 我们不能使用互操作
  2. 数据应该只有一个-sheet
  3. 该进程不应使用超过 5GB 的内存(耗时最多 45 分钟)
  4. Excel 文件处理库应该是免费的
  5. 我们不想创建 CSV 文件

以下是我已经尝试过的方法:

  1. OpenXML(内存不足异常,如果尝试使用大量 Ram 写入少量数据)
  2. ClosedXML(它使用了太多的 ram)
  3. EPPlus(它使用了太多内存)

我该怎么做?

我做了一些非常的轻度挖掘并找到了this。除此之外,我找不到任何符合指定要求的内容。

考虑到以下 link Excel specifications,您在 sheet 中可以拥有的总行数是 1,048,576。不可能在单个 sheet.

中加载 1000 万行

考虑到这一点,您确实有以下选项,以 CSV 格式导出数据(使用像 CsvHelper), and create a Excel sheet having a connection to that file (you can check how to do it here TechNet Article 这样的库)

你可以试试这个

for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
    for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
    {
        data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
        xlWorkSheet.Cells[i + 1, j + 1] = data;
    }
}

通过使用数据集

A reference to related article.

终于,我找到了解决问题的方法 Excel 只是一个 zip 文件,具有格式和工作表的文件夹结构。

下面是创建 excel 的最佳方法,我测试了很多库,这是最快的,消耗更少的内存并且不需要依赖项。

下面是 link 代码: https://github.com/danielgindi/SpreadsheetStreams.net

这里使用纯XML结构来写excel。