EPPlus 添加 VBA 代码损坏了生成的 xlsx 文件

EPPlus Adding VBA Code Corrupts resulting xlsx file

我正在使用来自数据表的 EPPlus 创建一个 excel 文件并将其保存到一个文件中,所有这些都相当标准。这没有任何麻烦。但是,如果我创建一个 vba 项目并添加任何 vba 代码,生成的 .xlsx 文件会突然损坏。当尝试使用 2013 打开它时,您会收到标准错误。

"Excel cannot open the file 'xyz.xlsx' because the file format or file extension is not valid. Verify that the file extension matches the format of the file.

如果我将扩展名更改为 .xls,文件可以正常打开,脚本也可以正常运行。我正在使用 Epplus (4.5.0.1) 的最新测试版。我应该只更改文件扩展名并坚持使用 .xls,还是有什么不对?

ExcelPackage.Workbook.CreateVBAProject()
ExcelPackage.Workbook.CodeModule.Code = "'Script is here"
Dim FInfo as new FileInfo("C:\Myfiles\ThisFile.xlsx")
ExcelPackage.SaveAs(FInfo)

您不能将 VBA 代码添加到 XLSX 文件格式。 看看here

.xlsx:

The default XML-based file format for Excel 2007-2013. Cannot store Microsoft Visual Basic for Applications (VBA) macro code or Microsoft Office Excel 4.0 macro sheets (.xlm).

也看看here 查看不同格式之间的差异:

XLSM If you include VBA macros in your XLSX file, you will be asked to change the file extension to XLSM. Only that way you can save your macro within the Excel file (there are other file types possible, e.g. XLSB – but you can’t use XLSX for VBA macros)

将您的文件保存为 XLSM,它应该可以工作。