【问题标题】:C# How do I append a Cell to every Row in a Excel Sheet using OpenXmlWriter (OpenXML SDK 2.5)C# 如何使用 OpenXmlWriter (OpenXML SDK 2.5) 将单元格附加到 Excel 工作表中的每一行
【发布时间】:2017-11-07 12:08:52
【问题描述】:

我有一个非常大的 Excel 文件,我需要在其中每行追加 100 个新单元格。 因为 OpenXML DOM 方法给了我一个 OutOfMemory 异常,所以我需要为我的项目使用 OpenXmlWriter。

谁能告诉我如何使用 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) });
                }

【问题讨论】:

    标签: c# excel openxml openxml-sdk


    【解决方案1】:
    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 文档链接

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多