[英]Can't download excel file with phpspreadsheet
我在PHP中使用angular 6,並且想使用phpspreadsheet下載Excel文件。
當我使用默認代碼
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
該文件無需下載即可生成到php文件夾,並且工作正常。 現在,我想下載它並選擇保存位置。
我使用在文檔中找到的代碼
// redirect output to client browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
在我的PHP文件的開頭,我有
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
我在Angular中的服務是:
export_excel(localUserid, date, projectid) {
return this.http.post(this.apiUrl, {localUserid, date, projectid},
{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
我將一些值傳遞給PHP。 我試圖在Angular中更改標題,但沒有任何效果。 有人知道如何解決嗎? 謝謝。
在嘗試了許多不同的解決方案之后,我找到了使用Angular 6和PHPSpreadsheet下載excel文件的正確方法。
首先,在PHP中,我必須將文件保存在本地:
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$file_name = 'D:\wamp64\www\angular6-app\client\download_excel\hello_world.xlsx'; //it depends where you want to save the excel
$writer->save($file_name);
if(file_exists($file_name)){
echo json_encode(array('error'=>false, 'export_path'=>'download_excel/' . 'hello_world.xlsx')); //my angular project is at D:\wamp64\www\angular6-app\client\
}
然后,我更改了excel.service.ts :
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
interface excel {
error: any,
export_path: any
}
@Injectable({
providedIn: 'root'
})
export class ExcelService {
apiUrl = "http://localhost/angular6-app/api/exportexcel.php";
constructor(private http: HttpClient) { }
export_excel(localUserid, date, projectid) {
return this.http.post<excel>(this.apiUrl, {localUserid, date, projectid},
{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
}
最后,如果一切正常,我將在用戶的角度組件中將用戶重定向到導出路徑 :
this.srv.export_excel(localUserid, date, projectid).subscribe((data) =>
{
location.href = data.export_path;
}
現在,我已經在我的下載文件夾中下載了excel。
我已經嘗試過此代碼,並且工作正常。 代碼在Symfony和javascript中,如下所示:
我的數組是這樣的:
$reportData=[
[
'a'=>'abc','b'=>'xyz'
] ,
[
'a'=>'mno','b'=>'pqr'
]
];
我已經使用了PHPOffice庫。 所以我使用了這些類:
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
//現在,Controller的Symfony代碼開始:
private function generateAlphabets($al) {
$char = "";
while ($al >= 0) {
$char = chr($al % 26 + 65) . $char;
$al = floor($al / 26) - 1;
}
return $char;
}
function generateExcel(){
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$header=[];
$coloumn=[];
$k=0;
foreach ($reportData[0] as $key=> $value) {
$header[]=$this->generateAlphabets($k);
$coloumn[]=$key;
$k++;
}
foreach ($coloumn as $key=>$value) {
$cell = $header[$key].'1';
$sheet->setCellValue($cell, $value);
}
$htmlString = '<table>';
$htmlString.='<tr>';
foreach ($coloumn as $value) {
$htmlString.="<th>".$value."</th>";
}
$htmlString.='</tr>';
foreach ($reportData as $index=>$array) {
$htmlString.='<tr>';
foreach ($array as $key => $value) {
$htmlString.="<td>".$array[$key]."</td>";
}
$htmlString.='</tr>';
}
$htmlString .= '</table>';
$internalErrors = libxml_use_internal_errors(true);
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->loadFromString($htmlString);
$writer = new Xlsx($spreadsheet);
$fileName="Excel_List_".(time()).".xlsx";
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$file_name = $fileName; //it depends where you want to save the excel
$writer->save($file_name);
chmod($file_name, 0777);
if(file_exists($file_name)){
return new JsonResponse(['error'=>false, 'export_path'=>'/','file'=>$fileName]);
}
}
public function removeExcel(Request $request){
$file = !empty($request->get('file'))?json_decode($request->get('file'),true):[];
$status=false;
if(!empty($file)){
if(file_exists($file)){
unlink($file);
$status=true;
}
}
return new JsonResponse(['success'=>$status]);
}
下載Java腳本代碼:
$.ajax({url: "/generateExcel", success: function(arrData){
var link = document.createElement("a");
link.download = arrData['file'];
link.href =arrData['export_path']+arrData['file'];
document.body.appendChild(link);
link.click();
var fileName = arrData['export_path']+arrData['file'];
document.body.removeChild(link);
$.ajax({
type: "POST",
url: "removeExcel",
data: {'file':fileName},
dataType: "text",
success: function(resultData){
}
});
}});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.