我正在尝试使用以下代码删除行:
SpreadsheetDocument document = SpreadsheetDocument.Open( "test.xlsx", true );
IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where( s => s.Name == "sheet1" );
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = ( WorksheetPart )document.WorkbookPart.GetPartById( relationshipId );
IEnumerable<Row> rows = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>();
Row row = rows.FirstOrDefault<Row>();
row.Remove();
worksheetPart.Worksheet.Save();
document.Close();
但我得到的只是清洁第一个细胞。我需要删除其他行的偏移行。 我怎么能这样做?
答案 0 :(得分:0)
我解决了这个问题。
注意:
我没有太多经验,因此以下代码可能无效
Row row = rows.FirstOrDefault<Row>();
row.Remove();
string cr;
foreach ( Row rowElement in rows )
{
rowElement.RowIndex.Value -= 1;
IEnumerable<Cell> cells = rowElement.Elements<Cell>().ToList();
if ( cells != null )
{
foreach ( Cell cell in cells )
{
cr = cell.CellReference.Value;
int indexRow = Convert.ToInt32( Regex.Replace( cr, @"[^\d]+", "" ) ) - 1;
cr = Regex.Replace( cr, @"[\d-]", "" );
cell.CellReference.Value = $"{cr}{indexRow}";
}
}
}