export file php to xls uses class PHPExcel - php

I want to export some file php to XLS file use class PHPEXcel, I don't used this before.
notif on my browser:
"Fatal error: Allowed memory size of 25165824 bytes exhausted (tried to allocate 1056 bytes) in C:\AppServ\www\kjjp2\Classes\PHPExcel\Cell.php on line 1124"
code:
<?php
include "config/koneksi.php";
error_reporting(E_ALL);
require_once 'Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$query = "SELECT * FROM `tabeldata`";
$hasil = mysql_query($query);
// Set properties
$objPHPExcel->getProperties()->setCreator("Erik")
->setLastModifiedBy("Erik")
->setTitle("Office 2007 XLSX ")
->setSubject("Office 2007 XLSX ")
->setDescription("Document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Jenis Report')
->setCellValue('B1', 'Pembayaran')
->setCellValue('C1', 'No')
->setCellValue('D1', 'Cabang')
//and some files
->setCellValue('AG1', 'Surveyor');
$rowNya = 3;
$no = 0;
while($row=mysql_fetch_array($hasil)){
$no = $no +1;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue("A$rowNya", $row['jenReport'])
->setCellValue("B$rowNya", $row['pembayaran'])
->setCellValue("C$rowNya", $row['no'])
->setCellValue("D$rowNya", $row['cabang'])
->setCellValue("E$rowNya", $row['namaSales'])
->setCellValue("F$rowNya", $row['jenLaporan'])
//and some files
->setCellValue("AG$rowNya", $row['surveyor']);
$rowNya = $rowNya + 1;
}
// Rename sheet
$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 (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="database.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>

You are running out of RAM that can be used by PHP. You can set how much RAM that PHP will use in php.ini. You currently have this limit set to 24MB, which is pretty low. Try increasing it.
ini_set('memory_limit', '256M');

PHPExcel is known for being memory hungry. The website has a discussions with some workarounds, see http://phpexcel.codeplex.com/discussions/242712?ProjectName=phpexcel
You could also consider using another library like the old Spreadsheet_Excel_Writer lib (which has its drawbacks as well)
http://pear.php.net/package/Spreadsheet_Excel_Writer/redirected

Related

PHPExcel fails on a heavy file import

I am trying to import excel files (xlsx) using PHPExcel library and store the data in a database. Following is my code:
require_once $_SERVER['DOCUMENT_ROOT']."/application/views/subfolder/PHPExcel/Classes/PHPExcel/IOFactory.php";
$file_name = $_FILES['controlname']['tmp_name'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$inputFileName = $file_name;
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
When I import a 1MB+ file having more than 1000 records, the code fails without returning any error with a strange behavior. However when I reupload that file by splitting it into multiple excels such that each excel contains only 1000 records, the same code works successfully.
To test, I tried echoing some message before and after the following line:
$objPHPExcel = $objReader->load($inputFileName);
The message echoed before this line is printed, but the message written after this line does not work.
In order to allow heavy loads I have made settings of ini in MBs as well as GBs, but nothing works.
ini_set("pcre.backtrack_limit", "100000000");
ini_set("max_allowed_packet ", "2G");
ini_set("max_execution_time ", "20000");
ini_set('max_input_time','20000');
ini_set('memory_limit', '2G');
ini_set('upload_max_filesize','20M');
ini_set('post_max_size', '2G');
set_time_limit(0);

phpexcel save pdf using tcpdf having pdf width issue

i am using php excel tcpdf render to save file as pdf. pdf can save successfully but pdf only saving as A4 size and it cuts my columns. i have many columns so i need all columns on pdf. pdf width should be auto so it can generate pdf as per number of columns given. please have a look below is my code i tried. also i included image i taken from pdf generated. you can see my pdf width is fix so my content is cut. any suggestion
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
$rendererName = PHPExcel_Settings::PDF_RENDERER_TCPDF;
$rendererLibrary = 'tcpdf';
$rendererLibraryPath = '' . $rendererLibrary;
//echo $rendererLibraryPath;
// 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");
// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');
$objPHPExcel->getActiveSheet()->setShowGridLines(false);
//If used external excel file
$inputFile="xlsx_file/subcategory.xlsx";
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$worksheet->setShowGridLines(true);
$worksheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER );
$worksheet->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER );
$worksheet->getPageSetup()->setFitToPage(true);
$worksheet->getPageSetup()->setFitToWidth(1);
$worksheet->getPageSetup()->setFitToHeight(0);
// 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'
);
}
$rand = rand(1234, 9898);
$presentDate = date('YmdHis');
$fileName = "report_" . $rand . "_" . $presentDate . ".pdf";
// Redirect output to a client’s web browser (PDF)
header('Content-Type: application/pdf');
header('Content-Disposition: attachment;filename="'.$fileName.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->save('php://output');
exit;
Try setting the portrait visualization:
$objPHPExcel->getActiveSheet()
->getPageSetup()
->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT);
I was having the same problem and I had to deactivate the autoSize for the columns and set the width manually, like this:
$objPHPExcel ->getActiveSheet()->getColumnDimension('A')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('B')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('C')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('D')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('E')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('F')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('G')->setAutoSize(false);
$objPHPExcel ->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel ->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel ->getActiveSheet()->getColumnDimension('C')->setWidth(14);
$objPHPExcel ->getActiveSheet()->getColumnDimension('D')->setWidth(15);
$objPHPExcel ->getActiveSheet()->getColumnDimension('E')->setWidth(14);
$objPHPExcel ->getActiveSheet()->getColumnDimension('F')->setWidth(18);
$objPHPExcel ->getActiveSheet()->getColumnDimension('G')->setWidth(9);
After doing that, my pdf was printed like this:
The answer might be a little late, but I hope it helps you in the future.

PHPExcel not calculating formulas

So im kinda new to phpExcel and im making a sheet with data from a form(not done but will come) but i have a problem my formulas wont calculate i have tested preset formulas and import formulas from the code but none wont work all i get is 0 and protected mode and if i click editsheet and click on the cell where the formula is and hit enter it works and calculate it
<?php
/** Error reporting */
error_reporting(E_ALL);
/** PHPExcel */
include 'Classes/PHPExcel.php';
/** PHPExcel_Writer_Excel2007 */
include 'Classes/PHPExcel/Writer/Excel2007.php';
include 'Classes/PHPExcel/IOFactory.php';
// Load file if it doesn't exists
if (file_exists('Exceltime.xlsx'))
{
$objPHPExcel = PHPExcel_IOFactory::load('Exceltime.xlsx');
}
else
{
$objPHPExcel = new PHPExcel();
}
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C4', '10:00')
->setCellValue('D4', '18:00')
->setCellValue('E4', '01:30')
->setCellValue('F4', '=(D4-C4-E4)');
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C5', '10:00')
->setCellValue('D5', '18:00')
->setCellValue('E5', '01:30')
->setCellValue('F5', '=(D5-C5-E5)');
$objPHPExcel->getActiveSheet()->setTitle('TidsRapport Namn');
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="Tidsrapport Namn.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->setPreCalculateFormulas(TRUE);
$objWriter->save('php://output');
?>
So all it should do is import work clock hours Start/end/break and then the formula is calculating how many hours/minutes you work
also if there is a better way or something i should do im free to try it :)
A better answer is to actually use MS Excel date/time values rather than hoping that PHPExcel/MS Excel will guess that your string values like ('10:00') are supposed to be times.
As per the PHPExcel documentation
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C4', PHPExcel_Calculation_DateTime::TIMEVALUE('10:00'))
->setCellValue('D4', PHPExcel_Calculation_DateTime::TIMEVALUE('18:00'))
->setCellValue('E4', PHPExcel_Calculation_DateTime::TIMEVALUE('01:30'))
->setCellValue('F4', '=(D4-C4-E4)');
$objPHPExcel->getActiveSheet()->getStyle('C4:E4')
->getNumberFormat()
->setFormatCode('hh:mm');
$objPHPExcel->getActiveSheet()->getStyle('F4')
->getNumberFormat()
->setFormatCode('[hh]:mm');

Post/send values to cells in a Excel file and extract result from specific cell?

I have a Excel file stored on my webserver which i use as a calculator. I was wondering if it's any way possible to post/send values to specific cells and then extract the result from a specific cell? I would prefer to do this by PHP.
Use phpExcel, here's an example to open and modify your existing file:
<?php
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/Lisbon');
set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');
include 'PHPExcel/IOFactory.php';
$fileType = 'Excel5'; //you may have to change this value
$fileName = 'yourfile.xlsm';
// Read the file
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($fileName);
// Change the file
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World!');
// Write the file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
$objWriter->save($fileName);
Please refer to the official documentation and list of examples.

PHPExcel not working with xls file

I am using PHPExcel to read excel file in php,it is working fine with xlsx but when try to read xls file,It shows an error
Fatal error: Call to undefined method PHPExcel_Reader_CSV::setReadDataOnly() in /var/www/....
Here is my code
$file_path='/var/www/html/site/sample.xls';
$inputFileType = PHPExcel_IOFactory::identify( $file_path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load( $file_path);
$total_sheets=$objPHPExcel->getSheetCount();
$allSheetName=$objPHPExcel->getSheetNames();
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow;++$row)
{
for ($col = 0; $col <$highestColumnIndex;++$col)
{
$value=$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
$arraydata[$row-1][$col]=trim($value);
}
}
The file that you're loading is identified as a CSV file, even though it has an .xls extension... it is quite a common practise for some developers to save files formatted as csv or with html markup with a .xls extension, but that doesn't make them BIFF-format .xls files.
The setReadDataOnly() method isn't available for the CSV Reader, because a CSV file cannot contain anything other than data.
The most recent versions of PHPExcel provide a stub for setReadDataOnly() in the CSV Reader to prevent an error in this situation, and I'd certainly recommend that you upgrade to the latest code; but if you can't do that, then the simplest fix for you is simply to wrap the call to setReadDataOnly() in an if test:
$inputFileType = PHPExcel_IOFactory::identify( $file_path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
if ($inputFileType !== 'CSV') {
$objReader->setReadDataOnly(true);
}
For binary Excel files (xls) you may have better luck using the (old) PHP-ExcelReader. It's the most reliable one I've found so far.

Categories