[英]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.我正在尝试在 .NET Core 6 中创建一个应返回 Excel 文件的端点。 The Problem is, that when i try to open the Excel File, it says the file format or extension is not valid.问题是,当我尝试打开 Excel 文件时,它说文件格式或扩展名无效。
That's my code:那是我的代码:
[HttpPost("/api/report")]
public async Task ExportFile([FromBody] ReportDTO reportDTO)
{
_excelService.GenerateReport(HttpContext, reportDTO);
}
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));
}
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.根据您的描述,我建议您可以直接使用内存流并使用 Fileresult 返回 Excel 文件。
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:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.