Javier Rincon
Javier Rincon

Reputation: 41

Change saving directory in phpspreadsheet

Im using PhpSpreadsheet to generate XLS files, all the functions work perfect except that it saves local files in temporary directories and I want to save them in a specific folder.

use PhpOffice\PhpSpreadsheet\IOFactory;
require __DIR__ . '/Header.php';

$spreadsheet = require __DIR__ . '/templates/MyTemplate.php';

$filename = $helper->getFilename("MyFilename", 'xls'); 
$writer = IOFactory::createWriter($spreadsheet, 'Xls');

$callStartTime = microtime(true);
$writer->save($filename);
$helper->logWrite($writer, $filename, $callStartTime);

But the output is located in

Write Xls format to /var/folders/pn/lyj970q90lq20mjv39bpgx_80000gn/T/phpspreadsheet/MyFilename.xls in 0.0640 seconds

Is there an other function to set the saving directory I want the files in?

Upvotes: 4

Views: 15630

Answers (4)

user20987344
user20987344

Reputation: 1

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

source https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#redirect-output-to-a-clients-web-browser

Upvotes: 0

Andika Trisna Adhi
Andika Trisna Adhi

Reputation: 55

Make sure these lines are commented out. Since this parameter will tell the server to export Xlsx as downloadable file. Not in specific custom location.

// Redirect output to a client’s web browser (Xlsx)
// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// header('Content-Disposition: attachment;filename="'.$FileName.'"');
// header('Cache-Control: max-age=0');
// // If you're serving to IE 9, then the following may be needed
// header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
// header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
// header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
// header('Pragma: public'); // HTTP/1.0

And finally you can save your file :

$writer->save("Location/Of/YourFolder".$YourFileName);

Upvotes: 0

Hal Egbert
Hal Egbert

Reputation: 98

On this line:

$filename = $helper->getFilename("MyFilename", 'xls'); 

Change to:

$filename = basename($helper->getFilename("MyFilename", 'xls')); 

This way, $filename will only contain the file name. Then you can insert your path and make it work as you want, as I did with mine:

$writer->save('C:/xampp/htdocs/tmp/' . $outputFileName);

Upvotes: 0

YurgenTM
YurgenTM

Reputation: 83

Use dot in path

$writer->save("./templates/MyFilename.xls");

Upvotes: 5

Related Questions