问题描述
限时送ChatGPT账号..从 api 路由:api/exportExcel,我想用 Core 2.0 和 EPPlus 生成一个 excel 文件,以便用户可以在他的机器上下载它,但文件没有生成,我没有服务器错误.另一方面,我在响应中有一个二进制内容:PK!rNäH¯3[Content_Types].xmlµÏJ1Æ_eÉU´D,等等...
From an api route : api/exportExcel, i want to generate an excel file with Core 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...
这是我的代码:
[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;
}
}
角度服务:
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', [])),
);
}
推荐答案
从ajax下载文件,可以试试下面的代码:
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>
更新:
对于 Angular 客户端,请尝试以下代码:
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();
});
这篇关于使用 .Net core 2 和 EPPlus 下载 excel 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论