Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a PhpSpreadSheet through button click

I'm trying to get my Laravel app to download an excel file with phpSpreadSheet a continuation of PhpExcel. But so far I'm not having any luck with it. I first tried to make an Axios call through an onClick but that didn't work since JS is not allowed to save things. After that I tried to attach the button to a Laravel action this just opened an empty page.

I don't know if anyone here will be able to help me but I will remain hopeful

like image 854
Ferdi van der Woerd Avatar asked Aug 17 '17 14:08

Ferdi van der Woerd


People also ask

How do I download PhpSpreadsheet?

Use composer to install PhpSpreadsheet into your project. Or also download the documentation and samples if you plan to use them. A good way to get started is to run some of the samples. Don't forget to download them via --prefer-source composer flag.

How to read Excel file using PhpSpreadsheet?

Read Excel File First, import the needed library and load the Reader of XLSX. Read the excel file using the load() function. Here test. xlsx is the file name.

How to write data in Excel file in PHP?

You may use the following code: header('Content-Type: application/vnd. ms-excel'); header('Content-Disposition: attachment;filename="file. xlsx"'); header('Cache-Control: max-age=0'); $writer->save('php://output');

How do I add a new line in a cell in Excel using PHP?

Write a newline character "\n" in a cell (ALT+"Enter") In Microsoft Office Excel you get a line break in a cell by hitting ALT+"Enter".


1 Answers

First you need to set an endpoint in your routes to call it using ajax (axios in your case):

Route::get('spreadsheet/download',[
   'as' => 'spreadsheet.download', 
   'uses' => 'SpreadsheetController@download'
]);

In your controller:

public function download ()
{
    $fileContents = Storage::disk('local')->get($pathToTheFile);
    $response = Response::make($fileContents, 200);
    $response->header('Content-Type', Storage::disk('local')->mimeType($pathToTheFile));
    return $response;
}

In case you don't have the file you can save it to php://output:

public function download ()
{
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="file.xlsx"');
    $writer->save("php://output");
}

Now you just need to call the endpoint /spreadsheet/download to start the download, but a normal <a href="/spreadsheet/download">Download</a> would work.

Hope this helps you.

like image 105
Asur Avatar answered Sep 20 '22 14:09

Asur