Не удается скачать файл Excel с phpspreadsheet - PullRequest
0 голосов
/ 03 февраля 2019

Я использую Angular 6 с PHP и хочу скачать файл Excel с помощью phpspreadsheet.

Когда я использую код по умолчанию

$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, но ничего не получалось.Кто-нибудь знает как это решить?Спасибо.

1 Ответ

0 голосов
/ 05 февраля 2019

Попробовав множество разных решений, я нашел правильный способ загрузки файла Excel с помощью Angular 6 и PHPSpreadsheet.

Прежде всего в 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, загруженный в папку «Загрузки».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...