使用epplus创build.xlsm文件

我试图让一个网站导出一个.xlsm文件,我似乎无法find任何有用的东西。 这里有一个简单的例子,我用它来testing构build一个.xlsx文件(工作)。

@using OfficeOpenXml; <html> <body> <div id="page-wrapper"> @{ // Change file extension to xlsm to test string fileExtension = "xlsm"; ExcelPackage p = new ExcelPackage(); p.Workbook.Worksheets.Add("Worksheet Name"); int LatestWorksheetNumber = p.Workbook.Worksheets.Count; ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber]; ws.Cells[1, 1].Value = "Test"; //Generate A File Byte[] bin = p.GetAsByteArray(); string filename = "filename"; try { //Download the file as an attachment Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.Cookies.Clear(); string ContentType = ""; if (fileExtension == "xlsx") { ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else { ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12"; } Response.GetType(); Response.ContentType = ContentType; Response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + fileExtension); Response.BinaryWrite(bin); Response.End(); <p>File Created</p> } catch (Exception e) { <p>@e.Message</p> } } </div> </body> </html> 

将文件扩展名更改为.xlsm后,会生成文件,但是当我尝试在Excel中打开文件时,出现错误,指出扩展名不正确。 我认为唯一需要改变的是内容types标题,但这显然不是问题。 我还有什么想念? 任何指导将不胜感激!

小鸭312钉了这个问题! 添加p.Workbook.CreateVBAProject(); before Byte[] bin = p.GetAsByteArray(); 解决了我的问题! 其他一切都保持不变,但Excel实际上将打开文件! 对于有同样问题的人来说,这是我的最终代码:

 @using OfficeOpenXml; <html> <body> <div id="page-wrapper"> @{ // Change file extension to xlsm to test string FileExtension = "xlsm"; ExcelPackage p = new ExcelPackage(); p.Workbook.Worksheets.Add("Worksheet Name"); int LatestWorksheetNumber = p.Workbook.Worksheets.Count; ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber]; ws.Cells[1, 1].Value = "Test"; p.Workbook.CreateVBAProject(); //Generate A File Byte[] bin = p.GetAsByteArray(); string filename = "filename"; try { //Download the file as an attachment Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.Cookies.Clear(); string ContentType = ""; if (FileExtension == "xlsx") { ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else { ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12"; } Response.GetType(); Response.ContentType = ContentType; Response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + FileExtension); Response.BinaryWrite(bin); Response.End(); <p>File Created</p> } catch (Exception e) { <p>@e.Message</p> } } </div> </body> </html>