OpenXML add new row to existing Excel file [closed]

微笑、不失礼 提交于 2019-11-29 17:27:00

问题


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 ?


回答1:


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 });
        }
    }



回答2:


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);


来源:https://stackoverflow.com/questions/6665307/openxml-add-new-row-to-existing-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!