NPOI Excel文件无效的文件格式或扩展
我正在尝试在.NET Core 6中创建一个应该返回Excel文件的端点。问题是,当我尝试打开Excel文件时,它说文件格式或扩展名无效。
那是我的代码:
控制器
[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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的描述,我建议您可以直接使用内存流并使用FileSult返回Excel文件。
更多详细信息,您可以参考以下示例:
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:
Result: