I am working with the Spreadsheet Library to create Excel files with PHP. My problem is that when I press the Excel icon on my WEB page, the file is not downloaded but is opened in a new tab in the browser, so far I have searched but I have not found anything I hope someone can guide me favour.
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$sheet = $spreadsheet->getActiveSheet()->setTitle('CALAMA');
header('Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="SOLICITUD
CALAMA.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
To achieve what you want, two things would be needed:
1. Use the correct header in the code
First of all, you would not be using the correct header for your content to display in the browser.
In the HTTP protocol, the header
Content-Disposition
is used to indicate whether the file should be downloaded, or displayed in the browser, as the documentation says :So regarding headers, for a file to open in the browser you have to use:
That is, change this:
For this:
For more details you can also see the documentation on MDN .
2. The browser can open Excel files
As @Marcos points out in his comment and @Ivandez in his answer, if your browser does not have an extension installed that allows you to open Excel files from the same, this will not work. If this is your case, see the following post , where several methods are explained to be able to view Excel from the browser.
Here is also a link to the Office extension in the Chrome Web Store (also courtesy of @Marcos).
You cannot do what you need because the browser is not able to interpret a spreadsheet and therefore cannot open an excel in another tab.
The author wants to open an excel in a new tab just as the browser opens an image or audio, it cannot be done since the browser is not capable of interpreting an excel.