OpenXML内存泄漏

时间:2012-11-12 17:01:16

标签: c# memory-leaks openxml

我使用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));
            }
        }

1 个答案:

答案 0 :(得分:1)

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