OpenXML add new row to existing Excel file [closed]
Asked Answered
T

2

14

I've got lots of XLSX files and I need to append a new row after the last one in the file. I'm using OpenXML and so far I know how to open/create spreadsheet, but my search for adding new rows to existing files returned nothing. Any ideas ?

Tonisha answered 12/7, 2011 at 13:54 Comment(0)
S
24

If all you need to do is add a blank row to the end and you don't care if a row already exists at the row index, then the following should work for you:

    public static void InsertRow(WorksheetPart worksheetPart)
    {
        SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();  
        Row lastRow = sheetData.Elements<Row>().LastOrDefault();
    
        if (lastRow != null)
        {
            sheetData.InsertAfter(new Row() { RowIndex = (lastRow.RowIndex + 1) }, lastRow); 
        }
        else
        {
            sheetData.Insert(new Row() { RowIndex = 0 });
        }
    }

For OpenXML SDK 2.5 (Runtime) v4.0.30319 there is no Insert method, thus use InsertAt as follows:

            ...
        }
        else
        {
            sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);
        }
    }
Semantic answered 12/7, 2011 at 17:59 Comment(4)
For OpenXML SDK 2.5 (Runtime) v4.0.30319 there is no Insert method, thus used InsertAt as follows: sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);Stuyvesant
@JanisS. 's comment seems fairly relevant. Maybe it can be added to the answer?Citadel
@Panzercrisis, added as answer, thanks!Stuyvesant
Thanks, it is still working as this wayStephi
S
7

If you use OpenXML SDK 2.5 (Runtime) v4.0.30319 there is no Insert method, but one can use InsertAt instead as follows:

sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);
Stuyvesant answered 19/5, 2017 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.