X
X
xmdv2020-05-14 11:26:04
excel
xmdv, 2020-05-14 11:26:04

How to insert rows into existing excel files 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);        
    }


I want to add a new line after the 5th line. But when I open the generated file in Excel 2016, the added row is not there.
Maybe someone knows how to correctly insert lines into existing .xlsx files? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question