如何使用OpenXML从Excel中删除行

问题描述 投票:2回答:1

我正在尝试使用以下代码删除行:

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

但我得到的只是清洁第一个细胞。我需要删除其他行的偏移行。我怎样才能做到这一点?

之前enter image description here之后enter image description here

我想得到什么:enter image description here

c# openxml
1个回答
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}";
                }
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.