简体   繁体   中英

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);
}

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM