Can';t下载带有PHPSReadSheet的excel文件

Can';t下载带有PHPSReadSheet的excel文件,php,angular,phpexcel,phpspreadsheet,Php,Angular,Phpexcel,Phpspreadsheet,我在PHP中使用angular 6,我想使用PHPSReadSheet下载一个excel文件 当我使用默认代码时 $writer = new Xlsx($spreadsheet); $writer->save('hello world.xlsx'); 该文件在不下载的情况下生成到php文件夹中,工作正常。现在我想下载它并选择保存它的位置 我使用在文档中找到的代码 // redirect output to client browser header('Content-Type: appl

我在PHP中使用angular 6,我想使用PHPSReadSheet下载一个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();
我在安格尔的服务是:

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 6phpsReadSheet下载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'
      } 
     })
  }
}

现在,我已将excel下载到我的下载文件夹中。

我已尝试过此代码,它工作正常。代码采用Symfony和javascript,如下所示:

我的数组是这样的:

我使用过PHPOffice库。所以我使用了这些类:

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

欢迎来到SO!即使你的答案是正确的,也试着对你的回答稍加评论,主要是在几乎所有的东西都是代码的时候。好的。我会牢记在心,并在未来的回答中给出更多细节。
$reportData=[
  [
     'a'=>'abc','b'=>'xyz'
  ] ,
  [
     'a'=>'mno','b'=>'pqr'
  ] 
];
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
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]);
}
$.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){

  }
});
  }});