I have issue when trying to download xlsx file. It works just fine when i test it locally, but when i upload it to production server, file gets corrupted.
this is code im using:
<?php
require 'conn.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', '#');
$sheet->setCellValue('B1', 'First');
$sheet->setCellValue('C1', 'Last');
$sheet->setCellValue('D1', 'Handle');
header('Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="text.xlsx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
die;
i tried changing header to, it did not help:
header('Content-type: application/vnd.ms-excel');
I think that will be ok if you add cleaning of the output buffer before you call createWriter static method.
ob_end_clean();
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
I had the same symptom and it was because the webserver continued to output things after doing
$writer->save('php://output');
In my case it was feasible to just do a die()
after it and the problem's gone. Maybe it can save somebody a little time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.