NPOI Excel文件下载损坏

时间:2017-10-08 17:53:45

标签: c# angularjs excel npoi mcafee

我正在尝试使用NPOI,angular2和web API将数据从数据表导出到Excel。我遵循的步骤是:1。将数据从数据表写入XLSX并将文件临时存储在服务器上,2。将其读入内存流并返回。我看到浏览器提示用户下载文件,文件下载后我收到一条错误信息说该文件已损坏。但是,当在步骤1之后打开服务器上的文件时,文件打开完全正常,通过文件浏览器下载后打开文件也可以正常工作。您能否帮我理解为什么在下载后从浏览器打开文件时会发生这种情况?

web 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));
            });
        }

角度组件代码:

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端点安全性。如何使我的下载与安全软件兼容?

1 个答案:

答案 0 :(得分:1)

好的,在探索之后,我可以通过禁用Chrome上的Mcaffee插件来获得excel下载。