Search code examples
.net-coreepplus

When saving .xlsm file in EPPlus 4.05, I get an error and then Excel deletes /xl/vbaProject.bin part


I get an error when I try the following code:

       //https://github.com/JanKallman/EPPlus/issues/31
        //Otherwise, I get an EPP error
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        //var excelFile = new FileInfo($"{keywordLocation.FilePath}{keywordLocation.FileName}".Replace("http://", ""));
        var excelFile = new FileInfo(@"wwwroot/SubmissionFiles/23477-1/Financial_Report_0001091596.xlsx");
        using (var source = new ExcelPackage(excelFile))
        {
            //source.Workbook.Worksheets.Add("VBA Sample");
            source.Workbook.CreateVBAProject();
            var sb = new StringBuilder();
            sb.AppendLine("Private Sub Workbook_Open()");
            sb.AppendLine("End Sub");
            source.Workbook.CodeModule.Code = sb.ToString();
            source.SaveAs(new FileInfo(@"wwwroot/SubmissionFiles/23477-1/Financial_Report_0001091596.xlsm"));
        }

Here's the error:

Problem in workbook error

When I click on OK, I get the following error:

Excel was able to open the file by repairing or removing the unreadable content

I've also tried this with the simplest VBA code consisting of a single comment: sb.AppendLine("'VBA Code");


Solution

  • Current EPPlus 4.5.3.2 still has the same problem... Don't even have to change the macro content

        using (var targetPackage = new ExcelPackage(new FileInfo(filename)))
        {
            var target = targetPackage.Workbook.VbaProject;
    ...
            targetPackage.Save();
       }
    

    and the result is incorrect for Excel 2016.