Download excel file with .Net core 2 and EPPlus

人走茶凉 提交于 2019-12-13 04:16:22

问题


From an api route : api/exportExcel, i want to generate an excel file with .netCore 2.0 and EPPlus so the user can download it on his machine but the file is not generated and i have no server error. On the other hand, i have a binary content in the response : PK!rNäH­¯3[Content_Types].xmlµÏJ1Æ_eÉU´D, etc...

Here's my code :

[HttpPost("exportBooks")]
public FileResult ExportBooks([FromBody] Books[] books)
{
        var comlumHeadrs = new string[]
        {
            "Book Id",
            "Name",
        };

        byte[] result;

        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("Current Book"); //Worksheet name
            using (var cells = worksheet.Cells[1, 1, 1, 5])
            {
                cells.Style.Font.Bold = true;
            }

            for (var i = 0; i < comlumHeadrs.Count(); i++)
            {
                 worksheet.Cells[1, i + 1].Value = comlumHeadrs[i];
            }

            //Add values
            var j = 2;
            foreach (var book in books)
            {
                 worksheet.Cells["A" + j].Value = book.BookId;
                 worksheet.Cells["B" + j].Value = book.name;
                 j++;
            }

            result = package.GetAsByteArray();

            var excelFile= new FileContentResult(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                 FileDownloadName = "book-export.xlsx"
            };

            return excelFile;
       }
  }

Angular service :

exportBooks(books: Book[]): Observable<Book[]> {    
    const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };

    return this.http.post<Book[]>(`${this.bookUrl}/exportBooks`, books, httpOptions).pipe(
       catchError(this.handleError('excelReport', [])),
    );

}


回答1:


For downloading file from ajax, you could try code below:

<script type="text/javascript">
        $(document).ready(function(){
            $.ajax({
                url: '/excelEbom',
                method: 'post',
                contentType:'application/json',
                xhrFields: {
                    responseType: 'blob'
                },
                success: function (data, status, response) {
                    var filename = "";
                    var disposition = response.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    }
                    let a = document.createElement('a');
                    a.href = window.URL.createObjectURL(data);
                    a.download = filename;
                    document.body.append(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            });
        });
    </script>

Update:

For Angular client, try code below:

const httpOptions = {
  headers: {
    'Content-Type': 'application/json'
  },
  observe: 'response' as 'body',
  responseType: 'blob' as 'json',
};

http.post(`${baseUrl}api/SampleData/excelEbom`, null, httpOptions).subscribe((response: HttpResponse<Blob>) => {
  var filename = "";
  var disposition = response.headers.get('Content-Disposition');
  if (disposition && disposition.indexOf('attachment') !== -1) {
    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    var matches = filenameRegex.exec(disposition);
    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
  }
  let a = document.createElement('a');
  a.href = window.URL.createObjectURL(response.body);
  a.download = filename;
  document.body.append(a);
  a.click();
});


来源:https://stackoverflow.com/questions/55231215/download-excel-file-with-net-core-2-and-epplus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!