sniperalex117
sniperalex117

Reputation: 79

Can't download excel file with phpspreadsheet

I use angular 6 with PHP and I want to download an excel file using phpspreadsheet.

When I use the default code

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

the file is generated to the php folder without being downloaded and works fine. Now I would like to download it and select where to save it.

I use the code that I found in the documentation

// 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');

but the file is not downloaded and I get this in my browser:enter image description here

At the begining of my PHP file I have

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

My service in Angular is:

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'
      } 
     })
  }

I pass some values to PHP. I tried to change the headers in Angular but nothing worked. Does anyone knows how to solve it? Thank you.

Upvotes: 3

Views: 6982

Answers (2)

Mohit Sidoliya
Mohit Sidoliya

Reputation: 184

I have tried this code and it's working fine. The code is in Symfony and Javascript which is shown here:

My array is like this:

$reportData=[
  [
     'a'=>'abc','b'=>'xyz'
  ] ,
  [
     'a'=>'mno','b'=>'pqr'
  ] 
];

I have used PHPOffice library. So I have used these classes:

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;

// Now the Symfony code for Controller starts:

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=[];
        $column=[];
        $k=0;
        foreach ($reportData[0] as $key=> $value) {
            $header[]=$this->generateAlphabets($k);  
            $column[]=$key;
            $k++;
        }

        foreach ($column as $key=>$value) {
            $cell = $header[$key].'1';
            $sheet->setCellValue($cell, $value);
        }

        $htmlString = '<table>';
        $htmlString.='<tr>';
        foreach ($column 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]);
}

Javascript code for download:

$.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){
      
  }
});
  }});

Upvotes: 1

sniperalex117
sniperalex117

Reputation: 79

After trying many different solutions, I found the correct way to download an excel file using Angular 6 and PHPSpreadsheet.

First of all in PHP I had to save the file locally:

$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\
}

Then, I changed my 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'
      } 
     })
  }
}

And finally in my angular component I redirect the user to my export path if everything worked correctly:

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

Now I have the excel downloaded in my downloads folder.

Upvotes: 2

Related Questions