使用指定列的OpenXml在Excel中插入新行

  • 本文关键字:Excel 插入 新行 OpenXml c#
  • 更新时间 :
  • 英文 :


这段代码运行良好,但我想做到这一点,我在excel文件中有3张表,所有表有不同的列大小,假设第一张有5列,第二张有3列,第三张有7因此,在表格的基础上,我想插入新行。就像如果第一张表有5列,那么数据只插入5列,如果第二个有3个,那么只有3个值像那样插入。那么,任何一位导游都可以我来做那件事。

using(FileStream fs = new FileStream(filepath, Filemode.Open, FileAccess.ReadWrite, 
FileShare.ReadWrite))
{
SpreadSheetDocument document = SpreadsheetDocument.Open(fs, false);
SharedStringTable sharedStringTable = 
document.WorkbookPart.SharedStringTablePart.SharedStringTable;
string cellValue = null;
foreach (WorksheetPart worksheetPart in document.WorkbookPart.WorksheetParts.Reverse())
{
int cnt = document.WorkbookPart.WorksheetParts.count();
foreach (SheetData sheetData in worksheetPart.Worksheet.Elements<SheetData>())
{
if (sheetData.HasChildren)
{
foreach (Row row in sheetData.Elements<Row>())
{
foreach (Cell cell in row.Elements<Cell>())
{
Row row = new Row();
row.Append(ConstructCell("firstvalue",CellValues.String));
sheetData.AppendChild(row);
WorksheetPart.Worksheet.Save();
}
}
}
}
}
}
document.Close();
Public static Cell ConstructCell(string value , CellValues datatype)
{
return new Cell(){CellValue = new CellValue(value),DataType = new EnumValue<CellValues> 
(datatype)};
}

我完成了。

//Replace this from
Row row = new Row();
row.Append(ConstructCell("firstvalue",CellValues.String));
sheetData.AppendChild(row);
WorksheetPart.Worksheet.Save();
//To this one ::
var rows = sheetData.Elements<Row>;
int rwCnt = rows.Count();
var clCnt = rows.First().ChildElements.Count();
for(int i = 0; i < 1 ; i++)
{
Row row  = new Row();
for(j = 0; j < clCnt; j++)
{
row.Append(
ConstructCell("firstvalue",CellValues.String)
)
}
sheetData.AppendChild(row);
WorksheetPart.Worksheet.Save();
}

最新更新