使用EPPlus excel文件下载WebApi – 打开 – 不可读的内容错误 – 修复

在我的extjs webclient上,我点击一个button,下载一个excel模板并填充数据。 当我点击CHROMEpopup来打开excel文件,它给了我下面的excel错误消息。 有谁知道我可以解决这个问题? 实际的文件看起来很好。

在这里输入图像说明

在这里输入图像说明

在这里输入图像说明

这是我的webapi代码

public HttpResponseMessage CreatePosSheet(string cName, string calcMethod, string username, int cid, HttpRequestMessage Request) { string templatePath = HttpContext.Current.Server.MapPath(@"~\tempLocation\"); string templateFileName = System.Configuration.ConfigurationManager.AppSettings["TemplateFileName"]; string templateName = string.Format("{0}{1}", templatePath, templateFileName); FileInfo xlTemplate = new FileInfo(templateName); HttpResponseMessage response; response = Request.CreateResponse(HttpStatusCode.OK); MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/octet-stream"); //MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.Content = new ByteArrayContent(ExcelSheet(xlTemplate, cName, calcMethod, username, cid)); response.Content.Headers.ContentType = mediaType; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = "Orders.xlsx"; return response; } 

这里是ExcelSheet的代码

  public byte[] ExcelSheet(FileInfo xlTemplate, string cName, string calcMethod, string username, int cid) { object[] tempObj = Orders(username, cid); List<TradeDetailDTO> tList = new List<TradeDetailDTO>(); List<TempClass> acctList = new List<TempClass>(); List<TempClass2> sectorList = new List<TempClass2>(); tList = tempObj[0] as List<TradeDetailDTO>; acctList = tempObj[1] as List<TempClass>; sectorList = tempObj[2] as List<TempClass2>; #region set column variables int colAcctNum = 1; int colAcctDesc = 2; int colAcctTrdLvl = 5; int colCname = 6; int rowCname = 15; #endregion using (var package = new ExcelPackage(xlTemplate)) { var worksheet = package.Workbook.Worksheets["Data"]; var wkshtFormula = package.Workbook.Worksheets["Formulas"]; wkshtFormula.Cells[rowCname, colCname].Value = cName; package.Save(); return package.GetAsByteArray(); } } 

你必须删除对.Save()的调用,因为它会closures.Save()作为副作用。 查看更多信息:

Shaman.EPPlus + ASP.NET核心MVC – 部分已经存在的exception