NPOI Excel file download corrupt

1.3k Views Asked by At

I am trying to export data from a data table to excel using NPOI, angular2 and web API. The steps I am following are - 1. Write data from data table to XLSX and store the file temporarily on the server, 2. Read this same and into a memory stream and return. I see that browser prompts the user to download the file, once the file is downloading I get an error saying the file is corrupt. However when the open the file on the server after step 1 the file opens perfectly fine, opening the file after download via the file explorer also works fine. Can you please help me understand why this is happening when the file is opened from the browser after download?

web api code:

  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 component code:

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

Edit:

I see that there is nothing wrong in the code which i am using, the issue is with mcAfee endpoint security installed on chrome. How can i make my download compatible with security software?

1

There are 1 best solutions below

0
On BEST ANSWER

Okay after poking around i was able to get the excel download to work by disabling the Mcaffee plugin on chrome.