我正在尝试使用LoadFromCollection方法将List发送到Excel文件。 生成XLSX文件后,它无法打开,但如果我将扩展名更改为XLS,则会显示如下。
[HttpGet]
[Route("GetExcel")]
public async Task<HttpResponse> GetExcel()
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
var stream = new MemoryStream();
using (var excelPackage = new ExcelPackage())
{
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add("SoftwareVersao");
var result = await _versaoAppService.Selecionar();
ws.Cells["A1"].LoadFromCollection(result);
ws.Cells.AutoFitColumns();
excelPackage.SaveAs(stream);
}
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + "SoftwareVersao.xlsx");
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
return HttpContext.Current.Response;
}
如果我更改下面的行生成上面的图像,则此代码会生成损坏的XLSX文件。
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + "SoftwareVersao.xls");
我做了几次尝试。
我做错了什么?有没有我忘了实施的东西?
我发现了这个问题,现在可以生成XLSX文件,但我遇到的问题是作者问题,Excel必须修复文件。