NPOI Excel 文件下载损坏

NPOI Excel file download corrupt

我正在尝试使用 NPOI、angular2 和网络 API 将数据从数据 table 导出到 excel。我遵循的步骤是 - 1. 将数据从数据 table 写入 XLSX 并将文件临时存储在服务器上,2. 将其读入内存流和 return。我看到浏览器提示用户下载文件,下载文件后我收到一条错误消息,提示文件已损坏。但是,当在第 1 步之后在服务器上打开文件时,文件打开得很好,通过文件资源管理器下载后打开文件也可以正常工作。你能帮我理解为什么下载后从浏览器打开文件时会发生这种情况吗?

网页api代码:

  public HttpResponseMessage ExportReport(ReportPostModel ReportModel)
            {
                try
                {
                    var dt = _IReportRepositoryObj.ExportToExcel(ReportModel.CommentsToExport, ReportModel.SelectedColumns);
                    var headers = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
                    ICellStyle cellStyle;
                    XSSFWorkbook workbook = new XSSFWorkbook();
                    cellStyle = workbook.CreateCellStyle();
                    XSSFFont hFont = (XSSFFont)workbook.CreateFont();
                    hFont.FontHeightInPoints = 12;
                    hFont.FontName = "Arial";

                    hFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                    cellStyle.SetFont(hFont);

                    var sheet = workbook.CreateSheet("sheet1");

                    var headerRow = sheet.CreateRow(0);

                    //Create header row
                    for (int i = 0; i < headers.Length; i++)
                    {
                        ICell cell = headerRow.CreateCell(i);
                        cell.SetCellValue(headers[i].ToString());
                    }

                    //dump data into the excel
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        IRow row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            ICell cell = row.CreateCell(j);
                            cell.SetCellValue(dt.Rows[i][headers[j]].ToString());
                        }
                    }
                    string fileName = "temp" + DateTime.Now.ToString("yyyyMMddHHmmssfff")+ ".xlsx";
                    string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Temp/");
                    filePath += fileName;

                    using (FileStream FWriteStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                    {
                        workbook.Write(FWriteStream);
                    }

                    //write excel into memory stream
                    using (var exportData = new MemoryStream())
                    {
                        using (FileStream FreadStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                        {
                            byte[] bytes = new byte[FreadStream.Length];
                            FreadStream.Read(bytes, 0, (int)FreadStream.Length);

                            FreadStream.Seek(0, SeekOrigin.Begin);
                            exportData.Write(bytes, 0, (int)FreadStream.Length);


                            HttpResponseMessage message = new HttpResponseMessage();
                            message.Content = new ByteArrayContent(bytes.ToArray());
                            message.Content.Headers.Add("x-filename", "temp.xlsx");
                            message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                            message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                            message.Content.Headers.ContentDisposition.FileName = "temp.xlsx";
                            message.StatusCode = HttpStatusCode.OK;
                            return message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }

angular service code:

    ExportReport(CommentSpecificationModel: any, SelectedColumns: any) {
            return Observable.create((observer: any) => {
                debugger;
                let req = new XMLHttpRequest();
                req.open('POST', apiBaseUrl ;
                let ReportModel = {
                    "CommentsToExport" : CommentSpecificationModel, 
                    "SelectedColumns" : SelectedColumns
                }


                req.setRequestHeader("Content-Type", "application/json");
                req.withCredentials = true;
                req.responseType = "blob";
                req.onreadystatechange = function () {
                    if (req.readyState == 4 && req.status == 200) {
                        debugger;
                        var contentType = req.getResponseHeader("content-type");
                        var blob = new Blob([req.response], { type: contentType });
                        observer.next(blob);
                        observer.complete();
                    }
                };
                req.send(JSON.stringify(ReportModel));
            });
        }

Angular 组件代码:

ExportDatatoExcel() {
        debugger;
        this.reportService.ExportSpecificationCommentReport(this.SpecificationCommentsModel, this.SelectedColumns).
            subscribe((data: any) => {
                debugger;
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(data);
                link.download = "Export.xlsx";
                link.click();
            }
            );
    }

编辑:

我发现我使用的代码没有任何问题,问题出在 chrome 上安装的 mcAfee 端点安全。如何使我的下载与安全软件兼容?

好吧,在四处寻找之后,我可以通过禁用 chrome 上的 Mcaffee 插件来下载 excel。