Answer the question
In order to leave comments, you need to log in
How to insert a row into an existing excel file using OpenXmlSDK?
I'm trying to insert a string into a '*.xlsx' file using the OpenXml SDK.
My code:
using var document = SpreadsheetDocument.Open("dspreadsheet.xlsx", true);
WorksheetPart worksheetPart = document.WorkbookPart.WorksheetParts.First();
var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
InsertRow(sheetData, 5);
worksheetPart.Worksheet.Save();
static void InsertRow(SheetData sheetData, uint rowIndex)
{
Row row = new Row();
Cell newCell = new Cell { DataType = CellValues.InlineString };
var inlineString = new InlineString();
var text = new Text { Text = "some text for cell" };
inlineString.Append(text);
newCell.AppendChild(inlineString);
row.AppendChild(newCell);
var retRow = sheetData.Elements<Row>().ElementAt((int)rowIndex);
sheetData.InsertAfter(row, retRow);
var rows = sheetData.Elements<Row>().ToArray();
uint idx = 0;
//here I set a sequentional RowIndex for each row
// if I do not use this code error described below remains
foreach (var r in rows)
r.RowIndex = ++idx;
}
Answer the question
In order to leave comments, you need to log in
try like this
using (var document = SpreadsheetDocument.Open("dspreadsheet.xlsx", true))
{
WorksheetPart worksheetPart = document.WorkbookPart.WorksheetParts.First();
var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
InsertRow(sheetData, 5);
worksheetPart.Worksheet.Save();
}
static void InsertRow(SheetData sheetData, uint rowIndex)
{
Row row = new Row();
Cell newCell = new Cell { DataType = CellValues.InlineString };
var inlineString = new InlineString();
var text = new Text { Text = "some text for cell" };
inlineString.Append(text);
newCell.AppendChild(inlineString);
row.AppendChild(newCell);
var retRow = sheetData.Elements<Row>().ElementAt((int)rowIndex);
sheetData.InsertAfter(row, retRow);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question