I am loading in an existing xlsm (macro-enabled) file, filling it with data, and outputting the stream to be downloaded by the user. When I do, Excel says it "cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
If I just pull the existing xlsm file and stream it out the controller, Excel is able to open it. The "corruption" only happens when I run it through EPPlus.
public Stream PopulateTemplateWithData()
{
using var package = new ExcelPackage(_templateStream);
var propName = package.Workbook.Names[PROP];
var propWorksheet = propName.Worksheet;
var propCell = propWorksheet.Cells[propName.Start.Row, propName.Start.Column];
propCell.Value = _inputData.Prop;
return package.Stream;
}
// Controller method
public IActionResult DownloadPopulatedWorkbook()
{
var stream = PopulateTemplateWithData();
return File(stream, "application/vnd.ms-excel.sheet.macroenabled.12", "example.xlsm");
}
The problem was that I wasn't calling package.Save()
or package.SaveAs(outputStream)
, so package.Stream
was not a complete, finalized Excel file.