使用OpenXml SDK删除Excel工作表中的表

时间:2018-11-16 20:12:21

标签: c# openxml openxml-sdk openxml-table

请提供c#代码以从工作表中删除Excel表。 谢谢!

1 个答案:

答案 0 :(得分:0)

以下是删除所有工作表中所有表格的代码:

 using (SpreadsheetDocument xl = SpreadsheetDocument.Open(targetFile, true))
        {
            WorkbookPart workbookPart = xl.WorkbookPart;
            foreach (WorksheetPart sheet in workbookPart.WorksheetParts)
            {
                List<TableDefinitionPart> TableDefinitionPartToDelete = new List<TableDefinitionPart>();
                var TableParts = sheet.Worksheet.WorksheetPart.Worksheet.Descendants<TablePart>();

                List<TablePart> TablePartToDelete = new List<TablePart>();

                foreach (var Item in TableParts)
                {
                    TablePartToDelete.Add(Item);
                }
                foreach (var tp in TablePartToDelete)
                {
                    tp.Remove();
                }

                foreach (TableDefinitionPart Item in sheet.TableDefinitionParts)
                {
                    TableDefinitionPartToDelete.Add(Item);
                }

                foreach (TableDefinitionPart Item in TableDefinitionPartToDelete)
                {               
                    sheet.DeletePart(Item);
                }
            }

            xl.Close();
        }