I am using the PHPSpreadsheet library to convert a generated XLSX file into a PDF. The XLSX conversion and download is working fine, but when I try to convert this XLSX into PDF I am getting empty PDF file, when I try to Opening it, it says the adobe reader/Web reader says "Could not open this file"
<?php
require_once(APPPATH .'third_party/phpspreadsheet/vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Exception;
use \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf
$spreadsheet = new Spreadsheet();
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->setActiveSheetIndex(0)->setCellValue('A1', 'Date')
->setCellValue('B1', 'XXXXX')
->setCellValue('C1', 'YYYY')
->setCellValue('D1', 'ZZZZZ')
->setCellValue('E1', 'XXXXX')
->setCellValue('F1', 'YYYY')
->setCellValue('G1', 'ZZZZ')
->setCellValue('H1', 'ZZZZZ');
// code to fill in the data
$spreadsheet->getActiveSheet()->fromArray($data["result_set"],null,'A2');
$writer = new Xlsx($spreadsheet);
IOFactory::registerWriter("PDF", Dompdf::class);
$pdfwriter = IOFactory::createWriter($spreadsheet, 'PDF');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;filename="01simple.pdf"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
Related
im trying to use phpspreadsheet to save some data from my db to an excel file. The problem is: when i create my sql object, my excel document just the format is not valid. When i delete the object, file opens normally. if i comment the line $psql = new PSql(); it may works fine.
require_once("funcoes/Psql.php");
require 'vendor/autoload.php';
$psql = new PSql();
$dados = $psql->getUltimoRegistro($_SESSION["contrato"]);
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$spreadsheet->getActiveSheet()
->setCellValue('A1', "Contrato")
->setCellValue('B1', "Código")
->setCellValue('C1', "Estatstica")
->setCellValue('D1', "Infração");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="result.xlsx"');
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
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 the file output:
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.
I had the same problem and ob_end_clean();solved my problem also. The last lines are below.
ob_end_clean();
$writer=new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'.urlencode($file_name).'"');
$writer->save('php://output');
I am trying to download excel file with pre-populated data using PhpSpreadsheet in laravel. But I am got empty file downloaded.Here`s my code.
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('B1','testing');
$writer = new Xlsx($spreadsheet);
$filename = 'tessa';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'. $filename .'.Xlsx"');
header('Cache-Control: max-age=0');
$writer->save($filename);
I tried dd($sheet) Here how it looks,it contains my data;
The file downloaded but empty file.Can any one tell me how to solve the issue?
You don't really need to set those headers. But if you must, edit filename to:
$filename = 'tessa.xlsx';
You need to change
$writer->save($filename);
to:
$writer->save('php://output');
I'm trying to add template in multiple sheets with phpexcel:
$sheet = $objPHPExcel->getActiveSheet();
//Start adding next sheets
$i=0;
while ($i < 10) {
$objPHPExcel = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objPHPExcel->load('template.xlsx'); // Empty Sheet
$objWorkSheet = $objPHPExcel->createSheet($i); //Setting index when creating
//Write cells
$objWorkSheet->setCellValue('A1', 'Hello'.$i)
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Rename sheet
$objWorkSheet->setTitle("$i");
$i++;
}
Unfortunately this doesn't work. I only get two sheets, sheet with template and sheet with "9" title
So this is the result (sheet titles[image]):
Sheet1 9
You can use PHPSpreadhsheet. This is what the currently deprecated PHPExcel library has been continued as.
Include the library in your .php file in the following way -
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
?>
You can set title by adding-
$spreadsheet->setActiveSheetIndex(0)->setCellValue('A1','Hello');
$spreadsheet->getActiveSheet()->setTitle('new');
$writer = new Xlsx($spreadsheet);
$filename = 'XXX';
header('Content-Disposition: attachment;filename="'. $filename .'.xls"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
PHPExcel's simple exmple is correctly working for me on my local machine setup. It is downloading .xlsx file and MS-Excel program happly opens it.
Now I copied this code to my WordPress plugin to allow Excel download from WordPress Admin section
if ( file_exists(CHECKIN_PLUGIN_DIR . '/lib/PHPExcel.php') ) {
ob_end_clean();
ob_start();
/** Include PHPExcel */
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel.php");
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel/Writer/Excel2007.php");
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("PHPExcel Test Document")
->setSubject("PHPExcel Test Document")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->save("/home/user/ExcelTests/test01.xlsx");
$objWriter->save('php://output');
exit;
}
?>
<div class="wrap">
....
But the file downloaded can not be opened by the excel, it says Different format than specified by the file extension.... and when opened shows bunch of hexa chars
PKU~AG�D�X�[Content_Types].xml��MN�0��"�%nY ��vAa �(0��ؖg�w{&i�#�nbE�{��y��d۸l m�����X�(���)���F��;#1_�����c)j�x/%��E��y� �QĿi!��K�
When I changed the code to save it as a file in hard disk, it can be opened without any issues.
if ( file_exists(CHECKIN_PLUGIN_DIR . '/lib/PHPExcel.php') ) {
ob_end_clean();
ob_start();
/** Include PHPExcel */
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel.php");
require (CHECKIN_PLUGIN_DIR . "/lib/PHPExcel/Writer/Excel2007.php");
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("PHPExcel Test Document")
->setSubject("PHPExcel Test Document")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("office PHPExcel php")
->setCategory("Test result file");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
/*
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
*/
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("/home/user/ExcelTests/test01.xlsx");
//$objWriter->save('php://output');
exit;
}
?>
<div class="wrap">
....
Same happend for Excel5 format too.
But the CSV downloaded via browser has no issues.
Any help?
Update
File downloaded vi browser is here
File saved to filesyestem is here
Found an additional line feed char 0A before PK in downloaded file when viewed in Hexa editor
I tried to remove that line feed using trim
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();
ob_start();
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
$ob_content = ob_get_contents();
ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="export.xlsx"');
header('Cache-Control: max-age=0');
echo trim($ob_content);
exit;
But even after that 0A is there at the start of file.
This almost certainly means that you're outputting something additional to the content of the xls file, such as white spaces or a BOM header. Open the file in a text editor, and look for any whitespace characters such as tabs, spaces, new lines, etc at the very beginning (before the PK characters) or end of the file, or for any obvious PHP error messages in the file itself.
I use this code on my project and this works well:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
$objWriter->save('php://output');