I am trying to create a PDF document using PHPexcel and MPDF library using the below code.But I get the error - "Adobe Reader could not open '01simple-6.pdf' because it is either not a supported file type or because the file has been damaged(for example, it was sent as an email attachment and wasn't correctly decoded)." What am I doing wrong?
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';
$rendererName = PHPExcel_Settings::PDF_RENDERER_MPDF;
$rendererLibrary = 'mpdf.php';
$rendererLibraryPath = dirname(__FILE__).'/../../MPDF56/' . $rendererLibrary;
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("PDF Test Document")
->setSubject("PDF Test Document")
->setDescription("Test document for PDF, generated using PHP classes.")
->setKeywords("pdf 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');
$objPHPExcel->getActiveSheet()->setShowGridLines(false);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
if (!PHPExcel_Settings::setPdfRenderer(
$rendererName,
$rendererLibraryPath
)) {
die(
'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
'<br />' .
'at the top of this script as appropriate for your directory structure'
);
}
// Redirect output to a client’s web browser (PDF)
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;filename="01simple.pdf"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->save('php://output');
exit;
Try turning off the error reporting. I had the same error, then I saw some notices and warnings that were output before the file output.
So I turned off the error reporting and it started to work .
Related
I was trying to export data to excel file with a QRcode within a cell.
I googled up and tried for clue.
Finally thought with adding a sample image file. then after with a phpqrcode image file.
It is still not succeeded can you please help me out.
Code:
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$gdImage = imagecreatefromjpeg('abstract_bg.jpg');
//Add a drawing to the worksheet
echo date('H:i:s') . " Add a drawing to the worksheet\n";
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('Sample image');$objDrawing->setDescription('Sample image');
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setHeight(150);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
// Set document properties
$objPHPExcel->getProperties()->setCreator("Jimson Jose")
->setLastModifiedBy("Jimson Jose")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("For minimizing work force by jimson, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Rewards");
// 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);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
When generating a file, you should make no debug output like
echo date('H:i:s') . " Add a drawing to the worksheet\n";
because it corrupts binary output.
If you remove this line, your code will work.
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel */
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$gdImage = imagecreatefromjpeg('abstract_bg.jpg');
//Add a drawing to the worksheet
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('Sample image');$objDrawing->setDescription('Sample image');
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setHeight(150);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
// Set document properties
$objPHPExcel->getProperties()->setCreator("Jimson Jose")
->setLastModifiedBy("Jimson Jose")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("For minimizing work force by jimson, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Rewards");
// 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);
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
I would also recommend removing error reporting from this script:
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
I have a code in php CodeIgniter that extracts data from database and generates an xls file via PHPExcel.
The problem is that whenever I upload the code into another server, it generates an .xls file with 0kb, and the error while opening is:
"Excel cannot open the file "____" because the file format or file extension not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file".
The incoming data is from same table and all the libraries used are also same.
My questions:
1. Are there any r/w permission applied by the server which makes the phpexcel file 0kb? I am using CodeIgniter.
2. Is there any way to see what is written in the PHPExcel object?
3. Are there any things I am missing out?
My code that generates xls file is:
// Set header and footer. When no different headers for odd/even are used, odd header is assumed.
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BInvoice&RPrinted on &D');
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');
// Set page orientation and size
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$this->load->library('PHPExcel/PHPExcel_IOFactory');
$file_name = $uri_year . "-" . $uri_month . "_staff_report.xlsx";
// Redirect output to a client web browser (Excel2007)
//ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename=' . $file_name);
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
// ob_end_clean();
$objWriter->save('php://output');
Thank you in advance.
My output as displayed in the test server is:
Solution:
It turns out that the php version of the server1 is 5.2.9
The php version of server2 is 5.1.6
Error generated in server2:
Fatal error: Class 'ZipArchive' not found in /var/www/html/APP_NAME/application/libraries/PHPExcel/Writer/Excel2007.php on line 225
The ZipArchive module requires php version >5.2
After the update, it works.
Thank you guys for your suggestions.
It outputs 0kb or "Excel cannot open the file "_ because the execution of the script encountered unusual error. Enable your error reporting, put this at the top of your script:
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
Yes, you may need to check the proper r/w permission and ownership of PHPExcel.php but the output file does not need anymore.
I have tested your code and it works fine..
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
/** Include PHPExcel */
require_once('PHPExcel.php');
$objPHPExcel = new PHPExcel();
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Set header and footer. When no different headers for odd/even are used, odd header is assumed.
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BInvoice&RPrinted on &D');
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');
// Set page orientation and size
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
// $this->load->library('PHPExcel/PHPExcel_IOFactory');
$uri_year = "2015";
$uri_month = "now";
$file_name = $uri_year . "-" . $uri_month . "_staff_report.xlsx";
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', "This is a test");
// Redirect output to a client web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename=' . $file_name);
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// ob_end_clean();
$objWriter->save('php://output');
?>
You may need to check if you have the right libraries for Excel2007, i have changed it to Excel5, but you can use Excel2007 and it works fine for me.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
please check following code tested:
public function demo()
{
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
/** Include PHPExcel */
$this->load->library('PHPExcel');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("MokNathal")
->setLastModifiedBy("MokNathal")
->setTitle("STAFF REPORT")
->setSubject("STAFF REPORT")
->setDescription("STAFF REPORT")
->setKeywords("STAFF REPORT")
->setCategory("STAFF REPORT");
$objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
$objPHPExcel->setActiveSheetIndex(0)
->getCell('A1')->setValue("Name of staff:aaaaaa Lname");
$objPHPExcel->getActiveSheet()->getStyle('A1:F1')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->mergeCells('A2:F2');
$objPHPExcel->setActiveSheetIndex(0)
->getCell('A2')->setValue("Group:Sunday Holiday Plan");
$objPHPExcel->getActiveSheet()->getStyle('A2:F2')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->mergeCells('A3:F3');
$objPHPExcel->setActiveSheetIndex(0)
->getCell('A3')->setValue("Login Details");
$objPHPExcel->getActiveSheet()->getStyle('A3:F3')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->mergeCells('A4:F4');
$objPHPExcel->setActiveSheetIndex(0)
->getCell('A4')->setValue("Checkin time:09:05:00am");
$objPHPExcel->getActiveSheet()->getStyle('A4:F4')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A4')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A5')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A5', 'Year')
->setCellValue('B5', 'Month')
->setCellValue('C5', 'Day')
->setCellValue('D5', 'Login Time')
->setCellValue('E5', 'Logout Time')
->setCellValue('F5', 'Login Status');
$objPHPExcel->getActiveSheet()->getStyle('A5:F5')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A5')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B5')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('C5')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('D5')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E5')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('F5')->getFont()->setBold(true);
$i=6;
$uri_year=2071;
$uri_month=4;
for($j=1;$j<=30;$j++)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i, $uri_year)
->setCellValue('B'.$i, $uri_month)
->setCellValue('C'.$i, $j);
$i++;
}
foreach(range('A','F') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->setTitle('Trasaction List');
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=".$uri_year."-".$uri_month."_staff_report.xlsx\"");
header("Cache-Control: max-age=0");
$objWriter->save("php://output");
}
I am taking the example from phpexcel
I just tried with passing value in GET Method, I am done with that.
Now i am trying to add image in the a3 coloumn.
Reference Code :
<?php
$value = $_GET['value'];
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', $value)
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', 'Miscellaneous glyphs')
->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
Example Code for inserting image :
$gdImage = imagecreatefromjpeg('images/officelogo.jpg');
// Add a drawing to the worksheetecho date('H:i:s') . " Add a drawing to the worksheet\n";
$objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
$objDrawing->setName('Sample image');$objDrawing->setDescription('Sample image');
$objDrawing->setImageResource($gdImage);
$objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
$objDrawing->setHeight(150);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
But i don't understanding how to insert the jpg in the a3 coloumn or any other coloumn in the excel file that i import.
How can i do this ?
Specifying coordinates for the image might help, as per the examples and the documentation
$objDrawing->setCoordinates('A3');
Note that an image isn't in a cell/column/row, but overlaid over the main sheet at the same position as that cell/column/row
Read my article,
http://www.7codes.info/post/8/export-excel-files-with-images-using-php-excel-library
$objDrawing = new PHPExcel_Worksheet_Drawing(); //create object for Worksheet drawing
$objDrawing->setName('Customer Signature'); //set name to image
$objDrawing->setDescription('Customer Signature'); //set description to image
$signature = $reportdetails[$rowCount][$value]; //Path to signature .jpg file
$objDrawing->setPath($signature);
$objDrawing->setOffsetX(25); //setOffsetX works properly
$objDrawing->setOffsetY(10); //setOffsetY works properly
$objDrawing->setCoordinates($column.$cell); //set image to cell
$objDrawing->setWidth(32); //set width, height
$objDrawing->setHeight(32);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); //save
I solve logo or images insert/showing problem use below code:
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('test_img');
$objDrawing->setDescription('test_img');
$objDrawing->setPath('../images/logo.png');
$objDrawing->setCoordinates('A1');
//setOffsetX works properly
$objDrawing->setOffsetX(5);
$objDrawing->setOffsetY(5);
//set width, height
$objDrawing->setWidth(100);
$objDrawing->setHeight(35);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
I try to use PHPExcel library for my report, this is my first time i use PHPExcel ,but error dialog appear telling that file format / extension invalid ,this is the syntax :
include '../_class/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Rizal")
->setTitle("Laporan Anggota")
->setSubject("anggota")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Create the worksheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A7', "No")
->setCellValue('B7', "NIS")
->setCellValue('C7', "NISN")
->setCellValue('D7', "Name")
->setCellValue('E7', "J.K")
->setCellValue('F7', "Birth")
->setCellValue('G7', "Address")
->setCellValue('H7', "Job")
// Redirect output to a client’s web browser (Excel2007)
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Test.xlsx"');
header('Cache-Control: max-age=0');
anyone can help me to solve it?
Try this example
<?php
$name = rand('0','10000').'.xlsx';
$n = rand('0','100');
error_reporting(E_ALL);
include 'PHPExcel/Classes/PHPExcel.php';
include 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
$o = new PHPExcel();
$o->getProperties()->setCreator('Creator');
$o->getProperties()->setLastModifiedBy('Last Modified');
$o->getProperties()->setTitle("Office 2007 XLSX Document ");
$o->getProperties()->setSubject('Subject');
$o->getProperties()->setDescription("Office 2007 XLSX, generated using PHP classes.");
$o->setActiveSheetIndex(0);
$o->getActiveSheet()->SetCellValue('A1', 'Name');
$o->getActiveSheet()->SetCellValue('B1', 'Rating');
$o->getActiveSheet()->SetCellValue('A2', 'Shawshank Redemption');
$o->getActiveSheet()->SetCellValue('B2', $n);
$o->getActiveSheet()->SetCellValue('A3', 'A Clockwork Orange');
$o->getActiveSheet()->SetCellValue('B3', $n);
$o->getActiveSheet()->setTitle('Films');
$objWriter = new PHPExcel_Writer_Excel2007($o);
$objWriter->save('excel/'.$name); // exce/ = filepath
?>
I think the problem you are having relates to the $objWriter variable.
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');