在现有的Excel文件中添加新行的OpenXML方法

14

我有很多XLSX文件,需要在文件的最后一行后添加一个新的行。我正在使用OpenXML,目前我知道如何打开/创建电子表格,但是我搜索添加现有文件的新行时没有找到任何结果。有什么想法吗?

2个回答

24
如果你只需要在末尾添加一行空白行,而且不关心该行索引上是否已经存在行,则以下代码适用于你:
    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 });
        }
    }

对于OpenXML SDK 2.5 (Runtime) v4.0.30319,没有Insert方法,因此请使用InsertAt,如下所示:

            ...
        }
        else
        {
            sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);
        }
    }

6
对于OpenXML SDK 2.5(运行时)v4.0.30319,没有Insert方法,因此使用InsertAt,如下所示: sheetData.InsertAt(new Row() { RowIndex = 0 }, 0); - Janis S.
2
@JanisS的评论似乎相当相关。也许可以将其添加到答案中? - Panzercrisis
1
@Panzercrisis,已作为答案添加,谢谢! - Janis S.
谢谢,它仍然以这种方式工作。 - balron

7

如果您使用的是OpenXML SDK 2.5 (Runtime) v4.0.30319版本,则没有Insert方法,但可以使用以下的InsertAt代替:

sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接