Use epplus to create .xlsm file

隐身守侯 提交于 2019-11-29 17:04:25

Xiaoy312 nailed the issue! Adding p.Workbook.CreateVBAProject(); before Byte[] bin = p.GetAsByteArray(); solved my issue! Everything else stayed the same but Excel will actually open the files now! Here's my final code for anyone who has the same issue:

@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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!