PHP Excel file downloaded via browser not opened by MS-Excel/OpenOffice - php

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

Related

phpexcel insert qrcode into excel and save it to client end

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

Adding Image to the Excel in phpexcel in php

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

PHPExcel Force Download Issue

I know this might have been asked in several pieces, but I could not find an exact answer to the issue. I am using PHPExcel to generate an Excel file (obviously), and the code works to generate the file, but not when I include the code for Force Download, it corrupts the file. My latest version of the script looks like this:
function make_xls_spreadsheet(){
/** Error reporting */
error_reporting(E_ALL);
/* Set the save path */
define('XLSX_SAVE_PATH', 'tmp/');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
/** PHPExcel */
include 'PHPExcel.php';
/** PHPExcel_Writer_Excel2007 */
include 'PHPExcel/Writer/Excel2007.php';
/* Create a new PHPExcel Object */
$objPHPExcel = new PHPExcel();
/* Add some metadata to the file */
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
/* Set active worksheet to first */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Segments');
/* Add some data to the worksheet */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
/* Write to server */
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$filename = "tony1.xlsx";
// Works fine up to here
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->save('php://output');
$objWriter->save(XLSX_SAVE_PATH . $filename);
readfile(XLSX_SAVE_PATH . $filename);
echo "DONE!";
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
}
Remember, when I remove the force code section, the file generates and I can FTP it down fine. However, doing both generating and forcing the file gives me a corrupt file. Normally I can click "Open & Repair" (Office2011 MacOSX) but obviously this is not desirable.
Could someone please help me understand:
Why it is being generated as corrupt? And why it works fine when I don't force download.
What the proper order for saving/forcing is (using PHP's header() function)
If there is a better way of doing this.
Much appreciated!!
**** Update **** Here is the code when I click "Fix & Repair":
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>Repair Result to tony1 03178.xml</logFileName>
<summary>Errors were detected in file 'Macintosh HD:Users:tony.diloreto:Downloads:tony1.xlsx'</summary>
<additionalInfo><info>Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.</info></additionalInfo>
</recoveryLog>
// answer actually belongs to #Dagon
The answer is actually straightforward, only needing a simple exit(); call.
Final code block:
function make_xls_spreadsheet(){
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
/** PHPExcel */
include 'PHPExcel.php';
/** PHPExcel_Writer_Excel2007 */
include 'PHPExcel/Writer/Excel2007.php';
/* Create a new PHPExcel Object */
$objPHPExcel = new PHPExcel();
/** Determine filename **/
$filename = "tony1.xlsx";
/** Set header information **/
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
/* Add some metadata to the file */
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
/* Set active worksheet to first */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Segments');
/* Add some data to the worksheet */
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->SetCellValue('D2', 'world!');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit();
}
This spits out the excel file to the browser:
readfile(XLSX_SAVE_PATH . $filename);
and then you spit this out, which becomes PART of the excel file as downloaded by the browser
echo "DONE!";
essentially you're sending
[excel data]DONE!
when Excel is expecting only
[excel data]
Try to modify File.php like this :
protected static $_useUploadTempDirectory = TRUE;
in folder phpexcel/Classes/PHPExcel/Shared (it's not the best way but it worked for me).

File format or extension invalid PHPExcel

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.

Error while creating a PDF document with PHPexcel+Mpdf

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 .

Categories