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 ?
我有很多XLSX文件,我需要在文件中的最后一行后添加一个新行。我正在使用OpenXML,到目前为止我知道如何打开/创建电子表格,但我在现有文件中添加新行的搜索没有返回任何内容。有任何想法吗 ?
2 个解决方案
#1
14
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
4
If you use OpenXML SDK 2.5 (Runtime) v4.0.30319 there is no Insert
method, but one can use InsertAt
instead as follows:
如果您使用OpenXML SDK 2.5(运行时)v4.0.30319,则没有Insert方法,但可以使用InsertAt,如下所示:
sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);
#1
14
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
4
If you use OpenXML SDK 2.5 (Runtime) v4.0.30319 there is no Insert
method, but one can use InsertAt
instead as follows:
如果您使用OpenXML SDK 2.5(运行时)v4.0.30319,则没有Insert方法,但可以使用InsertAt,如下所示:
sheetData.InsertAt(new Row() { RowIndex = 0 }, 0);