2017-11-07 36 views
0

非常に大きなExcelファイルがあり、各行に100個の新しいセルを追加する必要があります。 OpenXML DOMアプローチは私にOutOfMemory例外を与えているので、私は自分のプロジェクトにOpenXmlWriterを使う必要があります。C#OpenXmlWriter(OpenXML SDK 2.5)を使用してExcelシートのすべての行にセルを追加する方法

OpenXmlWriterを使用してセルに行を追加する方法を教えてもらえますか?

これは、DOMのアプローチを使用して私のコードです:

   int nRowCounter = 0; 
       foreach (Row row in sheetData.Elements<Row>()) 
       { 
        // skip first row 
        nRowCounter++; 
        if (nRowCounter == 1) 
         continue; 


        string uniqueID = row.Elements<Cell>().First().InnerText; 


        string[] branchenOfId = crmConnector.GetBranchenFromCrm(uniqueID, ""); 

        if (listSelectedBranchen.Any() && !branchenOfId.Intersect(listSelectedBranchen).Any() && nBranchenIndex == 1) 
        { 
         rowsToRemove.Add(row.RowIndex.Value); 
         continue; 
        } 

        string cellValue = ""; 

        if (branchenOfId.Contains(strName)) 
         cellValue = strName; 

        row.Append(new Cell() { DataType = CellValues.String, CellValue = new CellValue(cellValue) }); 
       } 

答えて

0
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, true)) 
{ 

WorkbookPart workBookPart = spreadsheetDocument.WorkbookPart; 

WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart; 
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); 
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); 

//You can retrieve a specific sheet also by the following code 
IEnumerable<Sheet> sheets = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Sheet Name"); 

//find the first row in the sheet data 
Row row1 = sheetData.GetFirstChild<Row>(); 

//create a new cell 
//I is the column and 1 is the Row Index 
// I assume you know how to get the last column of any row. 
//Just get the next alphabet letter and add the row index to make a CellReference. 
//e.g. If last cell of the Row is H, you can get the next letter i-e I 
Cell cell = new Cell() { CellReference = "I1" }; 
CellFormula cellformula = new CellFormula(); 
cellformula.Text = "IF(A2 = A1,1,0)"; 
cell.Append(cellformula); 

//append the cell to the row 
row1.Append(cell); 
} 

はまたthisドキュメントリンク

+0

これは、DOMのアプローチで見ています。しかし、私はOpenXmlWriterを使う必要があります。 – Blouflash

+0

大きなファイルにOpenXmlWriterを使用するには、次のリンクをご覧ください。 http://polymathprogrammer.com/2012/08/06/how-to-properly-use-openxmlwriter-to-write-large-excel-files/これは例で説明されています。 –

関連する問題