Sándor Hatvani
Sándor Hatvani

Reputation: 465

A sheet removal causes an unreadable file error in OpenXML

I try to remove a sheet from an Excel file and I have tried a lots of source from Internet but I always get the same result: unreadable content.

The link of the last one: https://blogs.msdn.microsoft.com/vsod/2010/02/05/how-to-delete-a-worksheet-from-excel-using-open-xml-sdk-2-0/

I also tried this:

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

Plus this:

sheet.RemoveAllChildren()

But the file is always corrupt.

Please!

UPDATE

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

Upvotes: 0

Views: 835

Answers (1)

Szymon Seliga
Szymon Seliga

Reputation: 824

A potential solution to your answer may be an empty (and not needed) CalculationChainPart. For more details see this answer

Upvotes: 1

Related Questions