Search code examples
c#asp.net-corenpoi

NPOI Excel File invalid file format or extension


I'm trying to create an Endpoint in .NET Core 6 that should return a Excel File. The Problem is, that when i try to open the Excel File, it says the file format or extension is not valid.

That's my code:

Controller

[HttpPost("/api/report")]
public async Task ExportFile([FromBody] ReportDTO reportDTO)
{
    _excelService.GenerateReport(HttpContext, reportDTO);
}

Service

public void GenerateReport(HttpContext httpContext, ReportDTO reportDTO)
{
    IWorkbook workbook;
    workbook = new XSSFWorkbook();
    ISheet excelSheet = workbook.CreateSheet("Test");

    IRow row = excelSheet.CreateRow(0);
    row.CreateCell(0).SetCellValue("Test");
    row.CreateCell(1).SetCellValue("Hello");

    row = excelSheet.CreateRow(1);
    row.CreateCell(0).SetCellValue(1);
    row.CreateCell(1).SetCellValue("World");

    workbook.WriteExcelToResponse(httpContext, GetFileName(reportDTO));
}

Extension Method

public static void WriteExcelToResponse(this IWorkbook book, HttpContext httpContext, string templateName)
{
    var response = httpContext.Response;
    response.ContentType = "application/vnd.ms-excel";
    if (!string.IsNullOrEmpty(templateName))
    {
        var contentDisposition = new Microsoft.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        contentDisposition.SetHttpFileName(templateName);
        response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
    }
    book.Write(response.Body);
}

Solution

  • According to your description, I suggest you could directly use memory stream and use Fileresult to return the Excel file.

    More details, you could refer to below example:

        [HttpPost("/api/report")]
        public ActionResult ExportFile(/*[FromBody] ReportDTO reportDTO*/)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet excelSheet = workbook.CreateSheet("Test");
    
            IRow row = excelSheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("Test");
            row.CreateCell(1).SetCellValue("Hello");
    
            row = excelSheet.CreateRow(1);
            row.CreateCell(0).SetCellValue(1);
            row.CreateCell(1).SetCellValue("World");
    
    
            using (var exportData = new MemoryStream())
            {
                workbook.Write(exportData);
                string saveAsFileName = string.Format("Export-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
                byte[] bytes = exportData.ToArray();
                return File(bytes, "application/vnd.ms-excel", saveAsFileName);
            }
    
        }
    

    Result:

    enter image description here