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.
Related
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);
I'm using the PHPExcel library in my project and its work fine when i wont to save files format (xls/xlsx). But I need to save files as a PDF format and i found some examples but none of them is working for me.
here the code which i use to generate file with pdf format
<?php
error_reporting(E_ALL);
ini_set('include_path', ini_get('include_path').';../Classes/');
include 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$inputFileName = 'file.xls';
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$objPHPExcel->setActiveSheetIndex(0);
$row = $objPHPExcel->getActiveSheet()->getHighestRow()+1;
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objSheet = $objPHPExcel->getActiveSheet();
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'test test');
$objWriter->save('test100.pdf');
?>
and here what the browser show me
( ! ) Fatal error: Uncaught exception 'PHPExcel_Writer_Exception' with message 'PDF Rendering library has not been defined.' in C:\wamp\www\projet\PHPExcel\Classes\PHPExcel\Writer\PDF.php on line 56
what did i do wrong
PHPExcel doesn't have a PDF Rendering library built-in as part of the code/distribution. Instead, it allows you to use any of 3 different 3rd party PDF libraries (tcPDF, DomPDF or mPDF).
You have to install that PDF Rendering library separately, and then you need to tell PHPExcel which PDF library you have installed before you can save a file as PDF.
This is explained in the PHPExcel documentation and shown in the examples like 21pdf.php
I want to read the data of .xlsx or .xls file in codeigniter. I have read the other questions related it but nothing works. I have used phpexcel, reader but with no luck. In my project i give the option to upload excel file then i want to read the data and insert it in the database.
Now i am using phpExcel library I have wrote:
$this->load->library('excel');
$reader= PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path=(FCPATH.'uploads/productfile/'.$_FILES['upload_file']['name']);
$excel=$reader->load($path);
$sheet=$excel->setActiveSheetIndex(0);
for($i=0;$i<=1000;$i++)
{
$col1= $sheet->getCellByColumnAndRow(0,$i)->getValue();
$col2= $sheet->getCellByColumnAndRow(1,$i)->getValue();
$col3= $sheet->getCellByColumnAndRow(2,$i)->getValue();
var_dump($col1);
}
but it display :
Uncaught exception 'PHPExcel_Exception' with message 'You tried to set
a sheet active by the out of bounds index: 0. The actual number of
sheets is 0 Please give me some example code.
The error
Please give me some example code:
Try this :
$sheet = $excel->getActiveSheet()->toArray(null,true,true,true);
This will return you an array of the current active sheet.Hope this helps.
This error is caused by a wrong initialization of the PHPexcel reader functionalities I suppose.
I usually do something like this to get the data from an excel:
require_once '../Classes/PHPExcel/IOFactory.php';
$filename = '../uploads/product/abc.xls';
$objPHPExcel = PHPExcel_IOFactory::load($filename);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
$total_rows = $highestRow-1;
for ($row = 2; $row <= $highestRow; ++ $row) {
//id
$cell = $worksheet->getCellByColumnAndRow(0,$row);
$id = $cell->getValue();
if(is_null($id)){$id = '#';}
}
Thanks to all for your suggestion:
I got the solution :
$file_data = $this->upload->data();
$file_path = './uploads/productfile/'.$file_data['file_name'];
include 'Classes/PHPExcel/IOFactory.php';
$inputFileName = $file_path;
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
'product'=$allDataInSheet[$i]["C"],
'brand'=$allDataInSheet[$i]["I"],
'standard'=$allDataInSheet[$i]["J"],
}
This extension of PHPExcel_IOFactory has issues with symbols like ™ Trademark, Copy Right, Degree etc.
You can't read a particular block if it contains such special characters.
This code segment works for me,
$this->load->library('excel');
$reader= PHPExcel_IOFactory::createReader('Excel2007');
$reader->setReadDataOnly(true);
$path= "./media/customer_exports/data-1558003506.xlsx";
$excel=$reader->load($path);
$sheet = $excel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($sheet);
for($i=2;$i<=$arrayCount;$i++)
{
echo $sheet[$i]["A"].$sheet[$i]["B"].$sheet[$i]["C"];
}
im using this few lines to convert an xlsx, which contain 4sheets to convert to .csv . but it only convert the first sheet of the xlsx file. how can i make it to convert every sheets in the xlsx. heres the code,
error_reporting(E_ALL);
date_default_timezone_set($this->vendor_timezone);
/** PHPExcel_IOFactory */
require_once sfConfig::get('sf_root_dir').'/lib/PHPExcel/IOFactory.php';
$file=sfConfig::get("sf_upload_dir").DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR."1344500254_MyExcel.xlsx";
// Check prerequisites
//print sfConfig::get("sf_upload_dir").DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR; exit;
if (!file_exists($file)) {
exit($file."Please run 06largescale.php first.\n");
}
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save(str_replace('.xlsx', '.csv',$file));
return "success";
Please check the tutorial here which has step by step code to achieve this
<?php
require_once 'PHPExcel/PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load("test123.xlsx");
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(";");
$writer->setEnclosure("");
$writer->save("test123.csv");
?>
To convert all sheets you must iterate through all worksheets and set it as the active sheet and then write that to a file.
$inFile = 'fileWithMultipleWorksheet.xlsx';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($inFile);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$index = 0;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$objPHPExcel->setActiveSheetIndex($index);
// write out each worksheet to it's name with CSV extension
$outFile = str_replace(array("-"," "), "_", $worksheet->getTitle()) .".csv";
$objWriter->setSheetIndex($index);
$objWriter->save($outFile);
$index++;
}
Write each sheet in turn to a different file, and then concatenate those files into one: PHPExcel does not provide an option to write multiple sheets to a single CSV file.
I need to aggregate 4 CSV files into a single, Excel workbook using PHPExcel.
Working on a single CSV file and a mono-spreadsheet workbook all works fine.
Using more than one CSV, I'm unable to get each CSV file into a seperate sheet.
How can I achieve this using PHPExcel?
There is an example of this in the Documentation/Examples/Readers directory in the SVN repository for PHPEXcel: It's Example #13
include 'PHPExcel/IOFactory.php';
$inputFileType = 'CSV';
$inputFileNames = array('./example1.csv','./example2.csv','./example3.csv','./example4.csv');
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$inputFileName = array_shift($inputFileNames);
$objPHPExcel = $objReader->load($inputFileName);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
foreach($inputFileNames as $sheet => $inputFileName) {
$objReader->setSheetIndex($sheet+1);
$objReader->loadIntoExisting($inputFileName,$objPHPExcel);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objPHPExcel->setActiveSheetIndexByName($loadedSheetName);
echo $loadedSheetName,PHP_EOL;
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
echo PHP_EOL;
}
You didn't specify exactly where the problem is...
For multiple worksheet excel file proceed as following:
Load CSV file
Create new worksheet
Write CSV to new worksheet
Go to 1
From docs:
If you need to create more worksheets in the workbook, here is how:
$objWorksheet1 = $objPHPExcel->createSheet();
$objWorksheet1->setTitle('Another sheet');
To set active worksheet:
$objWorksheet1->setActiveSheetIndex($index);