0

我使用 OpenXML 将数据表导出到 Excel 文件。

例如,我使用一个包含大约 250,000 行和大约 10 列的表。将其导出到 Excel 时,需要大约 1.2 GB 的内存,并且有时会抛出OutOfMemoryException.

我的问题有什么解决办法吗?

这是我的代码

        ExcelDocument excelDocument = new ExcelDocument();
        excelDocument.CreatePackage(exportFile);

        //populate the data into the spreadsheet
        using (SpreadsheetDocument spreadsheet =
            SpreadsheetDocument.Open(exportFile, true))
        {
            WorkbookPart workbook = spreadsheet.WorkbookPart;
            //create a reference to Sheet1
            WorksheetPart worksheet = workbook.WorksheetParts.Last();
            SheetData data = worksheet.Worksheet.GetFirstChild<SheetData>();

            //add column names to the first row
            Row header = new Row();
            header.RowIndex = (UInt32) 5;

            foreach (DataColumn column in table.Columns)
            {
                Stylesheet styleSheet = workbook.WorkbookStylesPart.Stylesheet;

                //build the formatted header style
                UInt32Value headerFontIndex =
                    createFont(
                        styleSheet,
                        "Arial",
                        9,
                        true,
                        System.Drawing.Color.White);
                //set the background color style
                UInt32Value headerFillIndex =
                    createFill(
                        styleSheet,
                        System.Drawing.Color.SlateGray);
                //create the cell style by combining font/background
                UInt32Value headerStyleIndex =
                    createCellFormat(
                        styleSheet,
                        headerFontIndex,
                        headerFillIndex,
                        null);
                Cell headerCell = createTextCell(
                    table.Columns.IndexOf(column) + 1,
                    5,
                    column.ColumnName, headerStyleIndex);

                header.AppendChild(headerCell);
            }
            data.AppendChild(header);

            //loop through each data row
            DataRow contentRow;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                contentRow = table.Rows[i];
                data.AppendChild(createContentRow(contentRow, i + 6));
            }
        }
4

1 回答 1

1

问题是在处理 SpreadsheetDocument 时花费了太多时间,似乎在处理时它会将所有数据刷新到 excel 表中,所以我吐出了创建的 excel 表,每个文件只生成 30,000 条记录,并强制垃圾收集器运行并解决了我的问题问题

于 2012-11-18T08:13:24.857 回答