Generating and downloading an excel file generates a ERR_INVALID_RESPONSE - php

This is my code:
public function downloadexcel($requestId) {
$this->loadModel('MaterialsRequest');
$materialsRequests = $this->MaterialsRequest->find('all', array('conditions' => array('MaterialsRequest.request_id' => $requestId)));
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();
// Set document properties
$objPHPExcel->getProperties()->setCreator("mez")
->setLastModifiedBy("mez")
->setTitle("Supply Template")
->setSubject("Supply Template")
->setDescription("Supply Template , please fill and upload.")
->setKeywords("office 2007 openxml php")
->setCategory("Supply");
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
$objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::VERTICAL_CENTER);
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Material ID')
->setCellValue('B1', 'Material Name')
->setCellValue('C1', 'Quantity')
->setCellValue('D1', 'Your offer');
$index = 2;
foreach ($materialsRequests as $oneMaterialsRequests) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A' . $index, $oneMaterialsRequests['MaterialsRequest']['material_id'])
->setCellValue('B' . $index, $oneMaterialsRequests['Material']['name'])
->setCellValue('C' . $index, $oneMaterialsRequests['MaterialsRequest']['qty'])
->setCellValue('E' . $index, $oneMaterialsRequests['MaterialsRequest']['id']);
$index++;
}
/// Set sheet security
$MaterialsRequestsNo = count($materialsRequests);
$MaterialsRequestsNo+=1; //add count for header
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
$objPHPExcel->getActiveSheet()
->getStyle('D2:D' . $MaterialsRequestsNo)
->getProtection()->setLocked(
PHPExcel_Style_Protection::PROTECTION_UNPROTECTED
);
// Miscellaneous glyphs, UTF-8
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Supply');
// 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="Supply.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;
}
From my local server operating on lamp when I call this function I can get the excel sheet and the web page would close after I call the function, when I'm calling it however on my apache server it brings out the error: ERR_INVALID_RESPONSE, I went through the code putting a die(); after each line to see how it would respond and up until putting a die() after $objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007'); it would download the spreadsheet but it would be corrupted and wouldn't close the page and it wouldn't bring up that error message, however apparently $objWriter->save('php://output'); is causing the error to come up, the page would freeze and the excel file wouldn't get downloaded.
I debugging someone else's code but I can't figure this part out.

Eventually the issue was in the ZipArchive class, that's why it worked on one server and didn't work on the other.
More documentation here: http://www.php.net/manual/en/zip.installation.php

I had the same problem. Check with "php -m" It gives you a list of modules and check if You have the "zip" module installed. http://php.net/manual/en/book.zip.php
This module is needed for PhpExcel. If you don´t have it, try to install or change your php version. In my case I solved changing my php from 7 to php 5.5

You can try saving to temp file and serving it with the redirect instead:
$objWriter->save('wwwroot/some-file.xlsx');
header("Location: /some-file.xlsx");
exit();

Now with php 7.4 you have to use --with-zip option

in php 7.4
//$objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;

Related

PHPExcel export not working : displays "the website cannot be reached"

I have cloned a project from server and installed in my local setup.
I am trying to export excel file to the browser using PHPExcel. It is working fine in the server. But there is problem with the local setup.
Also I checked number of columns and fields and they are fine.
Below is the code:
<?php
//PHPExcel starts from here
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Kathmandu');
if (PHP_SAPI == 'cli')
die('Error in loading PHPExcel');
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("GBD Admin")
->setLastModifiedBy("GBD Admin")
->setTitle("Weekly checkin/checkout log")
->setDescription("Test document for PHPExcel, generated using PHP classes.")
->setKeywords("Checkin/Checkout Logs")
->setCategory("Checkin/Checkout Logs");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Date of Export')
->setCellValue('B1', $now)
->setCellValue('A3', 'Employee Name')
->setCellValue('B3', ' Checkin-date')
->setCellValue('C3', ' Checkin-time')
->setCellValue('D3', ' Checkout-date')
->setCellValue('E3', ' Checkout-time')
// ->setCellValue('F3', ' Total-time Spent')
// ->setCellValue('G3', ' Over-time')
->setCellValue('F3', ' Early checkout-remarks')
->setCellValue('G3', ' Late checkin-remarks');
// Newly added statement below
// ->setCellValue('H3', ' Absent/Leave Remarks');
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A3:H3')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->fromArray($results, null, 'A5');
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(45);
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Login-data-' . $now);
// 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 (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Login_data_' . $now . '.xls"');
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, 'Excel5');
$objWriter->save('php://output');
exit;
?>
I have been getting this error:
This site can’t be reached
The webpage at http://localhost/gbdportal-new/Export might be
temporarily down or it may have moved permanently to a new web
address. ERR_INVALID_RESPONSE
It is working fine with the live version currently running on the server. What could be the problem?
This is a bug in phpExcel in combination with php7:
https://github.com/PHPOffice/PHPExcel/issues/716
on Line 581 of file PHPExcel/Classes/PHPExcel/Calculation/Functions.php there is a " break" , simply comment.

PhpExcel - Can't open the downloaded file

[This guy seems to have the same problem as me but it's Java and I don't understand anything :/ excel can not open the downloaded file through jsp ]
Hello everyone,
First of all, I want to say that English isn't my mother language so you might see some mistakes but I hope you will understand me.
So I'm a student and I have a 'student job', creating a website for a micro-bakery! They need to have a file with all their clients and I decided to use PhpExcel to generate it!
I did everything properly but it still doesn't work! I looked for help on google of course but nobody has the same error message as me. Here is what I get.
Error message I get when I try to open the file : In english : "Impossible to open the file "....xlsx" because it's format or extension is not valid. Please verify that the file is not broken and that it's extension match the file format"
The source code is here : `
if($action=="client-excel"){
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');
/** Include PHPExcel */
require_once '../libs/phpExcel/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("BakeryName")
->setLastModifiedBy("Clients")
->setTitle("Liste Clients ")
->setSubject("Liste Clients ")
->setDescription("Liste Clients ")
->setKeywords("Liste Clients ")
->setCategory("Liste Clients");
$toSupp=array();
$objPHPExcel->createSheet();
$array=array();
$array['header'][]="#client";
$array['header'][]="Nom";
$array['header'][]="Mail";
$array['header'][]="Nombre de pain(s) acheté(s)";
$array['data']=array();
$list = Client::getAllClients($order="id_client",$letter="",$valid=false,$start=0,$limit=100000); foreach($list as $client){
$client_array=array(
$client->getId(),
$client->getName(),
$client->getEmail(),
$client->getNbPainsCmd(),
);
$array['data'][]=$client_array;
}
if(sizeof($array['data'])==0){
$toSupp = $z;
}
$objPHPExcel->setActiveSheetIndex(0);
$j=0;
foreach($array['header'] as $h){
$objRichText = new PHPExcel_RichText();
$objRichText->createTextRun($h)->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow ($j,1, $objRichText);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn($j)->setAutoSize(true);
$j++;
}
for($i=0;$i<sizeof($array['data']);$i++){
for($j=0;$j<sizeof($array['data'][$i]);$j++){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow ($j,$i+2, $array['data'][$i][$j]);
}
}
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle("Liste clients");
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename.xlsx"');
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, 'Excel2007');
$objWriter->save('php://output');
exit;
}`
Thank you very much for all your potential answers!

Download an Excel file from web server folder

I am using PHPExcel to get Oracle SQL query results to an .xlsx file. I wrote my PHP code in node--18769.tpl.php and node--18769.tpl.xlsx file is downloading to webroot (/root/themes/bartik/templates) folder with result.
My requirement:
Can I rename node--18769.tpl.xlsx to report.xlsx?
Is it possible to prepend UNIX TIMESTAMP to file name? (like 1442223364_report.xlsx)
How can I download report.xlsx to my local system once after the file is generated?
This is my code:
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set document properties
// Add some data
$query = "SELECT DISTINCT TITLE, PID, TYPE, SUM(DAYCOUNT) AS tot, ROUND(SUM(DAYCOUNT)/( SELECT SUM(DAYCOUNT) FROM REPORT_LIST_VIEW), 4) AS per FROM REPORT_LIST_VIEW WHERE DAYCOUNT > '0' GROUP BY TITLE, PID, TYPE ORDER BY tot DESC";
//print $query; exit;
$res = db_query($query);
$rowNumber = 1;
while ( $dataFetched = $res->fetchAssoc() ) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$rowNumber, $dataFetched['title'])
->setCellValue('B'.$rowNumber, $dataFetched['tot'])
->setCellValue('C'.$rowNumber, $dataFetched['per']);
$rowNumber++;
}
// Miscellaneous glyphs, UTF-8
$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Page & Files Reports ');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
// 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);
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
Code updated:
$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;
This line
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
tells PHPExcel what filename to use when you save the file.... simply change it to
$objWriter->save("WHATEVER_YOU_WANT_TO_CALL_THE_FILE.xlsx);
If you want to download the file to local, then save to php://output and send the appropriate headers to the browser, exactly as described in the documentation and shown in the examples provided with PHPExcel
// write the file
$objWriter->save('Excel_report/'filename');
//Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Contact.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');
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;

PHPExcel generated file via $objWriter->save('php://output')- does it require permissions?

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

Opening excel document created by php

I have managed to create an excel document using php however I am getting an error everytime I open the document, even though everything else is fine. the error is the file you are trying to open is in different format than specified by the file extension ...
My code to export to excel:
public function actionExportToExcel() {
//header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="project-report-' . date('YmdHi') .'.xls"');
header("Content-Type: application/ms-excel");
$model=new ViewWebprojectreport('search');
$model->unsetAttributes(); // clear any default values
if(Yii::app()->user->getState('exportModel'))
$model=Yii::app()->user->getState('exportModel');
$dataProvider = $model->search(false);
$dataProvider->pagination->pageSize = $model->count();
// csv header
echo ViewWebprojectreport::model()->getAttributeLabel("StartDATE")."\t".
ViewWebprojectreport::model()->getAttributeLabel("PROJECT")."\t".
"Survey Number\t".
ViewWebprojectreport::model()->getAttributeLabel("ActualEndDate")."\t".
ViewWebprojectreport::model()->getAttributeLabel("OFFICE")."\t".
ViewWebprojectreport::model()->getAttributeLabel("PERCENT")."\t".
ViewWebprojectreport::model()->getAttributeLabel("PERCENTPlanned")."\t".
ViewWebprojectreport::model()->getAttributeLabel("KM")."\t".
ViewWebprojectreport::model()->getAttributeLabel("KMPlanned")."\t".
ViewWebprojectreport::model()->getAttributeLabel("COUNTRY")."\t".
ViewWebprojectreport::model()->getAttributeLabel("AREA")."\t".
ViewWebprojectreport::model()->getAttributeLabel("ASAAREA").
" \r\n";
// csv data
foreach ($dataProvider->getData() as $data) {
//if you want all data use this looop
/*foreach ($data as $key => $value) {
echo $value.",";
}
echo "\r\n";*/
echo "$data->StartDATE\t$data->PROJECT\t".$data->PROJCODE . $data->PROJID ."\t$data->ActualEndDate\t$data->OFFICE\t$data->PERCENT\t$data->PERCENTPlanned\t$data->KM\t$data->KMPlanned\t$data->COUNTRY\t$data->AREA\t$data->ASAAREA\t\r\n";
}
}
I do not want to export as csv but straight into excel format file. What am I missing?
This is because the file is actually basically just a CSV file with an XLS extension to make it open in Excel. See this Microsoft doc for more information: http://support.microsoft.com/kb/948615 - it happens in new versions of Excel. Older ones will happily export them.
The reason for doing it this way was because it is so much simpler to export a CSV file than an Excel one. I'd like to write a proper Excel exporter sometime, but that will take time to read and understand the Excel file format, and I've not had a chance to do that yet.
One option is simply to rename the file name to .csv, and keep the user interface as saying that it is an Excel file (Excel is quite happy to read csv files). Given that Windows tends to hide the file extension, this seems like a fairly attractive option.
It would be helpful solution for solving varied kinds of excel problems - link
let me know if i can help you more.
I used PHPExcel
$objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase', 'autoload'));
$objPHPExcel->getProperties()->setCreator(Yii::app()->user->__userInfo['name'])
->setLastModifiedBy(Yii::app()->user->__userInfo['name'])
->setTitle("Weekly Status")
->setSubject("Weekly Status");
$sheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$model=new ViewWebprojectreport('search');
$model->unsetAttributes(); // clear any default values
if(Yii::app()->user->getState('exportModel'))
$model=Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),true,false);
$dataProvider->pagination->pageSize = $model->count();
//data
foreach ($dataProvider->getData() as $data) {
//if you want all data use this looop
$highestColumn = "A";
foreach ($data as $key => $value) {
if(! in_array($key,array("id","PROCESSOR","DEPTCODE","PERCENTPlanned","MCSALE"))){
if($key == "name")
$key = "Client";
else
$key = ViewWebprojectreport::model()->getAttributeLabel("$key");
if($highestRow == 1){
$sheet->setCellValue($highestColumn.$highestRow,$key);
//Yii::log($key,"ERROR");
}
//echo $value.",";
if($highestRow == 1){
$highestRow++;
$sheet->setCellValue($highestColumn.$highestRow,$value);
$highestRow--;
}else
$sheet->setCellValue($highestColumn.$highestRow,$value);
$highestColumn++;
}
}
//Yii::log($highestRow,"ERROR");
if($highestRow == 1)
$highestRow++;
$highestRow++;
//echo "\r\n";*/
//echo "$data->StartDATE\t$data->ProjectEndDate\t$data->PROJECT\t".$data->PROJCODE . $data->PROJID ."\t$data->ActualEndDate\t$data->PROCESSOR\t$data->OFFICE\t$data->DEPTCODE\t$data->PERCENT\t$data->PERCENTPlanned\t$data->KM\t$data->KMPlanned\t$data->MC\t$data->MCSALE\t$data->CATEGORY\t$data->COUNTRY\t$data->AREA\t$data->PROJINFO\t$data->REGION\t$data->ASAAREA\t\r\n";
}
$filename = $_GET['type'].'statusreport_'.date('Y-m-d_H-i-s_T').'.xls';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
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, 'Excel5');
$objWriter->save(Yii::app()->params['exportToDir'].$filename);
$objWriter->save('php://output');
Yii::app()->end();

Categories