无法使用 phpspreadsheet 下载 excel 文件

Can't download excel file with phpspreadsheet

我将 angular 6 与 PHP 一起使用,我想使用 php 电子表格下载 excel 文件。

当我使用默认密码时

$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

文件未下载就生成到 php 文件夹并且工作正常。现在我想下载它并select保存它的位置。

我使用在文档中找到的代码

// 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 中的 headers 但没有任何效果。 有谁知道如何解决它? 谢谢。

在尝试了许多不同的解决方案后,我找到了使用 Angular 6[= 下载 excel 文件的正确方法38=]电子表格.

首先,在 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'
      } 
     })
  }
}

最后在我的angular组件中,如果一切正常,我将用户重定向到我的导出路径

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

现在我在我的 downloads 文件夹中下载了 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;

// 现在控制器的 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){

  }
});
  }});