Convert XLSM to XLSX

后端 未结 2 1346
遇见更好的自我
遇见更好的自我 2020-12-11 07:56

I\'m using the EPPLUS library to read data from Excel to create another file. Unfortunately it does not support the .XLSM extension file. Is there a nice way to convert .X

相关标签:
2条回答
  • 2020-12-11 08:32

    Using the Open XML SDK, like in amurra's answer, but in addition to changing doc type, VbaDataPart and VbaProjectPart should be removed, otherwise Excel will show error a file is corrupted.

    using (var inputStream = File.OpenRead("C:\\temp\\test.xlsm"))
    using (var outStream = new MemoryStream()) {
        inputStream.CopyTo(outStream);
        using (var doc = SpreadsheetDocument.Open(outStream, true)) {
            doc.DeletePartsRecursivelyOfType<VbaDataPart>();
            doc.DeletePartsRecursivelyOfType<VbaProjectPart>();
            doc.ChangeDocumentType(DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook);
        }
        File.WriteAllBytes("C:\\temp\\test.xlsx", outStream.ToArray());
    }
    
    0 讨论(0)
  • 2020-12-11 08:46

    In order to do this you will need to use the Open XML SDK 2.0. Below is a snippet of code that worked for me when I tried it:

    byte[] byteArray = File.ReadAllBytes("C:\\temp\\test.xlsm");
    using (MemoryStream stream = new MemoryStream())
    {
        stream.Write(byteArray, 0, (int)byteArray.Length);
        using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
        {
           // Change from template type to workbook type
           spreadsheetDoc.ChangeDocumentType(SpreadsheetDocumentType.Workbook);
        }
        File.WriteAllBytes("C:\\temp\\test.xlsx", stream.ToArray()); 
    }
    

    What this code does is it takes your macro enabled workbook file and opens it into a SpreadsheetDocument object. The type of this object is MacroEnabledWorkbook, but since you want it as a Workbook you call the ChangeDocumentType method to change it from a MacroEnabledWorkbook to a Workbook. This will work since the underlying XML is the same between a .xlsm and a .xlsx file.

    0 讨论(0)
提交回复
热议问题