![](/img/trans.png)
[英]How do I add a new sheet to an Excel .xlsx file using the OpenXML SDK v2.0 with c#?
[英]C# How do I append a Cell to every Row in a Excel Sheet using OpenXmlWriter (OpenXML SDK 2.5)
我有一個非常大的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) });
}
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);
}
還可以查看此文檔鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.