无法使用phpspreadsheet下载Excel文件

时间:2019-02-03 15:18:46

标签: php angular phpexcel 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');

但文件未下载,我可以在浏览器中找到它: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中更改标题,但没有任何效果。 有人知道如何解决吗? 谢谢。

2 个答案:

答案 0 :(得分:1)

尝试了许多不同的解决方案后,我找到了使用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下载到我的“下载”文件夹中。

答案 1 :(得分:1)

我已经尝试过此代码,并且可以正常工作。代码在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){

  }
});
  }});