无法使用phpspreadsheet下载excel文件

问题描述 投票:3回答:2

我在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');

但文件未下载,但我在浏览器中得到了此文件:enter image description here

在我的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中更改标题,但没有任何效果。有人知道如何解决吗?谢谢。

php angular phpexcel phpspreadsheet
2个回答
1
投票

尝试了许多不同的解决方案后,我找到了使用Angular 6PHPSpreadsheet下载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'
      } 
     })
  }
}

最后是在我的[中,如果一切正常,我将用户重定向到export path:

this.srv.export_excel(localUserid, date, projectid).subscribe((data) => { location.href = data.export_path; }
现在,我已经在

downloads文件夹中下载了excel。


0
投票
我已经尝试过此代码,并且可以正常工作。代码在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;
//现在,控制器的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){ } }); }});
© www.soinside.com 2019 - 2024. All rights reserved.