Angular 5 使用 post 请求下载 excel 文件
Angular 5 download excel file with post request
我遇到一个问题,我下载了一个 Excel 文件 Angular 1 但如果我在 Angular 5 中实现相同的代码,它会显示你的错误文件已损坏。我的回复在 ArrayBuffer 中,我无法读取文件。
下面是我的代码:
服务:
DownloadData(model:requiredParams):Observable<any>{
const headers = new Headers();
const requestOptions = new RequestOptions({ headers: headers });
requestOptions.headers.append('Content-Type', 'application/json');
const body = JSON.stringify(model);
return this.http.post(url, body, requestOptions)
.map((res:any) => res)
.catch((e: any) => Observable.throw(this.errorHandler(e)));
}
分量:
exportToExcel() {
this.loadingOverlayFlag = true;
this.podashboardService.DownloadData(this.data).subscribe(result=>{
console.log(result);
this.downloadFile(result._body,'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.xlsx');
})
}
downloadFile(blob: any, type: string, filename: string) {
var binaryData = [];
binaryData.push(blob);
const url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})); // <-- work with blob directly
// create hidden dom element (so it works in all browsers)
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
// create file, attach to hidden element and open hidden element
a.href = url;
a.download = filename;
a.click();
}
我可以下载文件,但无法读取其内容。错误是:
Microsoft Excel
Excel cannot open the file '███████ DASHBOARD (5).xlsx' because the file format or file extension is not valid.
Verify that the file has not been corrupted and that the file extension matches the format of the file. OK
我整天都在为这个问题苦苦挣扎。替换 angular HttpClient 并使用 XMLHttpRequest 如下:
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.setRequestHeader("content-type", "application/json");
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
if (arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
console.log(byteArray, byteArray.length);
this.downloadFile(byteArray, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.xlsx');
}
};
oReq.send(body);
然后在您的 downloadFile 函数中修改了 Blob 的创建:
const url = window.URL.createObjectURL(new Blob([binaryData]));
在您的情况下,服务将如下所示:
DownloadData(model:requiredParams):Observable<any>{
return new Observable(obs => {
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.setRequestHeader("content-type", "application/json");
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
var byteArray = new Uint8Array(arrayBuffer);
obs.next(byteArray);
};
const body = JSON.stringify(model);
oReq.send(body);
});
}
然后组件:
exportToExcel() {
this.loadingOverlayFlag = true;
this.podashboardService.DownloadData(this.data).subscribe(result=>{
// console.log(result);
this.downloadFile(result,'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet', 'export.xlsx');
})
}
downloadFile(blob: any, type: string, filename: string) {
var binaryData = [];
binaryData.push(blob);
const url = window.URL.createObjectURL(new Blob(binaryData, { type: filetype })); // <-- work with blob directly
// create hidden dom element (so it works in all browsers)
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
// create file, attach to hidden element and open hidden element
a.href = url;
a.download = filename;
a.click();
}
我设法通过使用 httpClient 使其工作(responseType: 'arraybuffer'
在 httpOptions 中成功了)。
createReportBackend() {
const httpOption: Object = {
observe: 'response',
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
responseType: 'arraybuffer'
};
this.httpClient.post('http://localhost:8080/api/report', this.data, httpOption)
.pipe(map((res: HttpResponse) => {
return {
filename: 'Drinks.xlsx',
data: new Blob(
[res['body']],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}
),
};
}))
.subscribe(res => {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(res.data, res.filename);
} else {
const link = window.URL.createObjectURL(res.data);
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = link;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(link);
a.remove();
}
}, error => {
throw error;
}, () => {
console.log('Completed file download.');
});
}
下载使用文件保护程序找到的 excel 文件的最简单方法在这里:
//Declaration
headers: HttpHeaders;
options: any;
//Constructor or u can have for specific method
this.headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.options = {
observe: 'response',
headers: this.headers,
responseType: 'arraybuffer'
};
//Service request:
this.httpClient.post('http://localhost:8080/api/report', this.data, this.option)
.pipe(
catchError(err => this.handleError(err))
).subscribe(response => {
Helper.exportExelFile(response, 'FileName');
});
//component or in helper function in one class
import * as FileSaver from 'file-saver';
function exportExelFile(data, filename) {
const blobValue = new Blob([data['body']], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
FileSaver.saveAs(blobValue, filename + '.' + FileType.EXCEL);
}
export const Helper = {
exportExelFile
};
我遇到一个问题,我下载了一个 Excel 文件 Angular 1 但如果我在 Angular 5 中实现相同的代码,它会显示你的错误文件已损坏。我的回复在 ArrayBuffer 中,我无法读取文件。
下面是我的代码:
服务:
DownloadData(model:requiredParams):Observable<any>{
const headers = new Headers();
const requestOptions = new RequestOptions({ headers: headers });
requestOptions.headers.append('Content-Type', 'application/json');
const body = JSON.stringify(model);
return this.http.post(url, body, requestOptions)
.map((res:any) => res)
.catch((e: any) => Observable.throw(this.errorHandler(e)));
}
分量:
exportToExcel() {
this.loadingOverlayFlag = true;
this.podashboardService.DownloadData(this.data).subscribe(result=>{
console.log(result);
this.downloadFile(result._body,'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.xlsx');
})
}
downloadFile(blob: any, type: string, filename: string) {
var binaryData = [];
binaryData.push(blob);
const url = window.URL.createObjectURL(new Blob(binaryData, {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})); // <-- work with blob directly
// create hidden dom element (so it works in all browsers)
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
// create file, attach to hidden element and open hidden element
a.href = url;
a.download = filename;
a.click();
}
我可以下载文件,但无法读取其内容。错误是:
Microsoft Excel
Excel cannot open the file '███████ DASHBOARD (5).xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file. OK
我整天都在为这个问题苦苦挣扎。替换 angular HttpClient 并使用 XMLHttpRequest 如下:
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.setRequestHeader("content-type", "application/json");
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
if (arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
console.log(byteArray, byteArray.length);
this.downloadFile(byteArray, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.xlsx');
}
};
oReq.send(body);
然后在您的 downloadFile 函数中修改了 Blob 的创建:
const url = window.URL.createObjectURL(new Blob([binaryData]));
在您的情况下,服务将如下所示:
DownloadData(model:requiredParams):Observable<any>{
return new Observable(obs => {
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.setRequestHeader("content-type", "application/json");
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
var byteArray = new Uint8Array(arrayBuffer);
obs.next(byteArray);
};
const body = JSON.stringify(model);
oReq.send(body);
});
}
然后组件:
exportToExcel() {
this.loadingOverlayFlag = true;
this.podashboardService.DownloadData(this.data).subscribe(result=>{
// console.log(result);
this.downloadFile(result,'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet', 'export.xlsx');
})
}
downloadFile(blob: any, type: string, filename: string) {
var binaryData = [];
binaryData.push(blob);
const url = window.URL.createObjectURL(new Blob(binaryData, { type: filetype })); // <-- work with blob directly
// create hidden dom element (so it works in all browsers)
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
// create file, attach to hidden element and open hidden element
a.href = url;
a.download = filename;
a.click();
}
我设法通过使用 httpClient 使其工作(responseType: 'arraybuffer'
在 httpOptions 中成功了)。
createReportBackend() {
const httpOption: Object = {
observe: 'response',
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
responseType: 'arraybuffer'
};
this.httpClient.post('http://localhost:8080/api/report', this.data, httpOption)
.pipe(map((res: HttpResponse) => {
return {
filename: 'Drinks.xlsx',
data: new Blob(
[res['body']],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}
),
};
}))
.subscribe(res => {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(res.data, res.filename);
} else {
const link = window.URL.createObjectURL(res.data);
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = link;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(link);
a.remove();
}
}, error => {
throw error;
}, () => {
console.log('Completed file download.');
});
}
下载使用文件保护程序找到的 excel 文件的最简单方法在这里:
//Declaration
headers: HttpHeaders;
options: any;
//Constructor or u can have for specific method
this.headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.options = {
observe: 'response',
headers: this.headers,
responseType: 'arraybuffer'
};
//Service request:
this.httpClient.post('http://localhost:8080/api/report', this.data, this.option)
.pipe(
catchError(err => this.handleError(err))
).subscribe(response => {
Helper.exportExelFile(response, 'FileName');
});
//component or in helper function in one class
import * as FileSaver from 'file-saver';
function exportExelFile(data, filename) {
const blobValue = new Blob([data['body']], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
FileSaver.saveAs(blobValue, filename + '.' + FileType.EXCEL);
}
export const Helper = {
exportExelFile
};