Ron*_*Ron 1 php download phpexcel angular
我在 PHP 中创建了帖子表单,单击按钮就会下载一个 excel 文件,并且我还有一些表单数据也发布到 URL 和文件,用于使用纯 HTML 成功下载并提交表单
在 PHP 中,这是当表单发布到文件时触发的函数
public function downloadExcel($fileName = '', $addTimeStamp = true) {
$fileName = (!$fileName) ? 'excel_download' : preg_replace('/\s+/', '_', $fileName);
if ($addTimeStamp) {
$fileName .= date('_d_m_Y_H_i_s');
}
$fileName .= '.xlsx';
$this->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: cache, must-revalidate');
header('Pragma: public');
$objWriter = PHPExcel_IOFactory::createWriter($this, 'Excel2007');
$objWriter->save('php://output');
}
Run Code Online (Sandbox Code Playgroud)
当它工作时,我在请求标头中设置了以下内容
响应中没有显示任何内容
但现在我们正在尝试将前端迁移到 Angular 框架,我们可以从中下载文件,我已经尝试过他的方法
downloadTheExport() {
this.downloadfile().subscribe((blob: any) => {
const blobdownload = new Blob([blob], { type: "application/vnd.ms-excel;charset=utf-8" });
saveAs(blobdownload, 'testdata.xls');
});
}
downloadfile(){
const formDataForExport: FormData = new FormData();
formDataForExport.append('export', 'ALL');
return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' }
});
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在 Angular 中下载此内容时,我观察到,当在 Angular 中进行调用时,Content-Type 的请求标头似乎已更改为,Content-Type: multipart/form-data; boundary angular并且当我在响应选项卡中看到它显示一些数据时,如下所示。
它Content-Type对于您的请求标头中的 是正确的,因为您确实通过 php 后端发布了 formDataForExport。
但处理响应的方式似乎是错误的。我提出以下解决方案可能会有所帮助:
假设您正在引用此 fileSaver:
https://github.com/Hipparch/file-saver-typescript/blob/master/file-saver.ts
建议包含并使用上面的脚本,因为要处理保存文件时的不同浏览器行为,它很复杂,不利于重新实现它们。
downloadTheExport() {
this.downloadfile().subscribe((resp: any) => {
const fileSaver: any = new FileSaver();
fileSaver.responseData = resp.body;
fileSaver.strFileName = 'testdata.xls';
fileSaver.strMimeType = 'application/vnd.ms-excel;charset=utf-8';
fileSaver.initSaveFile();
});
}
downloadfile() {
const formDataForExport: FormData = new FormData();
formDataForExport.append('export', 'ALL');
return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' },
responseType: 'blob',
observe: 'response'
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9540 次 |
| 最近记录: |