移除工作表会导致OpenXML中出现无法读取的文件错误

时间:2019-05-27 06:02:17

标签: c# excel openxml

我尝试从Excel文件中删除工作表,并且尝试了很多来自Internet的资源,但总是得到相同的结果:内容不可读。

最后一个的链接:https://blogs.msdn.microsoft.com/vsod/2010/02/05/how-to-delete-a-worksheet-from-excel-using-open-xml-sdk-2-0/

我也尝试过:

 Sheet sheet = workbook.WorkbookPart.Workbook.Descendants<Sheet>().First(s => s.Name.Equals(sheetName));
 sheet.Remove();
 workbook.WorkbookPart.Workbook.Save();

加上此:

sheet.RemoveAllChildren()

但是文件总是损坏的。

请!

更新

 using (MemoryStream xlsxStream = new MemoryStream())
 {
    using (var fileStream = File.OpenRead(templatePath))
       fileStream.CopyTo(xlsxStream);
    ...
    using (var workbook = SpreadsheetDocument.Open(xlsxStream, true, new OpenSettings { AutoSave = true }))
    {
       Sheet sheet = workbook.WorkbookPart.Workbook.Descendants<Sheet>().First(s => s.Name.Equals(sheetName));
       sheet.Remove();
       workbook.WorkbookPart.Workbook.Save();
       ...

0 个答案:

没有答案