My code works perfect with file.xlsx but I can't make it work with old file.xls. I tried every code I found and nothing works... I tried change the version of Excel2007to 2003,2004 but nothing... Don't know what else to try.
Here is my current code (working with file.xlsx but I need to work with file.xls too).
<?php
function load_table(){
require_once('Classes/PHPExcel.php');
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load("SampleData.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
echo '<table class="table">' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>';
$first = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
if($first[0] == '='){
echo $objWorksheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();
}
else
echo $first;
echo '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
}
?>
The Reader for xls files is the Excel5 Reader.
But you really should simply use the IOFactory's load() method, and let PHPExcel identify the filetype for itself and select the correct reader, because a lot of files (particularly those downloaded from the internet) that have an .xls extension aren't really BIFF format files.... PHPExcel can identify and load these correctly when using the load() method, because it can pick the correct Reader for itself.
But when you specify a Reader such as Excel2007 or Excel5 yourself, you're telling PHPExcel which Reader it must use, even though it may not be the correct Reader for the actual file.
Document link, which lists all of the different Readers by name
Related
I was working on an Yii2 API where i need to upload a .csv or .xlsx file and read from it using PHPExcel(DEPRECATED now , but i am stuck with it as new one PhpSpreadsheet requires PHP version 5.6 or newer) and return the array of data .
This was the code used in the API function
public function actionUpload()
{
$params = $_FILES['uploadFile'];
if($params)
{
$data = array();
$model = new UploadForm();
$model->uploadFile = $_FILES['uploadFile'];
$file = UploadedFile::getInstanceByname('uploadFile');
$inputFileName = $model->getpath($file,$data);
// Read your Excel workbook
try
{
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName['link']);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
if($inputFileType == 'CSV')
{
if (mb_check_encoding(file_get_contents($inputFileName['link']), 'UTF-8'))
{
$objReader->setInputEncoding('UTF-8');
}
else
{
$objReader->setInputEncoding('Windows-1255');
//$objReader->setInputEncoding('ISO-8859-8');
}
}
$objPHPExcel = $objReader->load($inputFileName['link']);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName['link'],PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$fileData = array();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
array_push($fileData,$rowData[0]);
// Insert row data array into your database of choice here
}
return $fileData;
}
}
But there are encoding issues when we upload a excel file containing hebrew data in it . As you can see the code below from the above code was used to address this issue
if (mb_check_encoding(file_get_contents($inputFileName['link']), 'UTF-8'))
{
$objReader->setInputEncoding('UTF-8');
}
else
{
$objReader->setInputEncoding('Windows-1255');
}
Later i found that UTF-8 and Windows-1255 are not the only possible encoding for the flies that may be uploaded but other encoding like UTF-16 or other ones depending upon the Operating System of user. Is there any better way to find the encoding other than using mb_check_encoding
The common error that occur during the process of reading the data in file is :
iconv(): Detected an illegal character in input string
As you can see the above error occurs due to the inability to detect the appropriate encoding of the file. Is there any workaround ?
You can attempt to use mb_detect_encoding to detect the file encoding but I find that results vary. You might have to manually specify a custom match order of encodings to get proper results. Here is an example substitute for the if statement in question:
if(inputFileType == 'CSV')
{
// Try to detect file encoding
$encoding = mb_detect_encoding(file_get_contents($inputFileName['link']),
// example of a manual detection order
'ASCII,UTF-8,ISO-8859-15');
$objReader->setInputEncoding($encoding);
}
Make sure the first clean the output buffer in your page:
ob_end_clean();
header( "Content-type: application/vnd.ms-excel" );
header('Content-Disposition: attachment; filename="uploadFile.xls"');
header("Pragma: no-cache");
header("Expires: 0");
ob_end_clean();
I am iterating all cells of the excel sheet and printing out the values. Same time i also want to print the font name they are using. Is there any function to get the specific cell font name in phpexcel ? Thanks.
below is the code snippet
include('lib/phpexcel/Classes/PHPExcel/IOFactory.php');
//Use whatever path to an Excel file you need.
$inputFileName = 'text.xlsx';
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());
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
foreach ($sheet->getRowIterator() as $row) {
echo '<tr>' . "\n";
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
// Is there any similar $cell->getFont() function ?? which will echo"time new roman"
echo '<td>' .$cell->getValue(). '</td>' . "\n";
}
echo '</tr>' . "\n";
}
?>
The font is an aspect of the style of a cell; so you need to get the style details for the cell, and read the font information from that:
$cell->getStyle()
->getFont()
->getName();
Note that you can also get font size, italic, bold, underlining, super/subscript, strikethru, and the font colour in a similar manner.... the font object holds more information than simply the font name.
I have an excel file with around 40 sheets with some of the cells defined by formulas.
I read the contents of a single sheet and display on the UI. After user modifies the same i save it back to the excel using phpExcel save.
But when i save PHPExcel save modifies all the sheets with some junk values where ever there is a formula cell.
for ($row = 2; $row <= $highestRow; $row++) {
//echo "row=".$row;
if((sizeof($convertedArr)-1) > $row){
$jsonRow = $convertedArr[$row];
$type = PHPExcel_Cell_DataType::TYPE_STRING;
$colWrite = 0;
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
if($sheet->getCellByColumnAndRow($col, $row)->getValue() != 'xxxxx'){
//$sheet->setCellValueByColumnAndRow($col, $row,$jsonRow[$col]);
$sheet->getCellByColumnAndRow($col, $row)->setValueExplicit($jsonRow[$colWrite], $type);
$colWrite++;
}
}
}else{
break;
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
if(is_writable($siteName)){
$objWriter->setPreCalculateFormulas(FALSE);
$objWriter->save($siteName);
}else{
echo "File is not Writable";
}
How can i handle this situation.
How can PHPExcel just save the sheet in question and not all the sheets.
I am NOT even looping through all the sheets.
Also, one more problem is after save the formatting such as background color is gone!
I 'm using ms excel to upload large data to my system. When I upload excel file which has columns made by recipe.The uploading progess is longer than usual.Now,I want to check valid the input excel file.If they have columns made by recipe, the system will cancel progess. I 've read phpexcel doucment, but not found any solution.
Do you have any ideas?
My source
My source:
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($uploaded_dir . DIRECTORY_SEPARATOR . $new_name);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$total_order_row = $highestRow;
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
for ($i = 1; $i <= $highestRow; $i++) {
$data1 = $objWorksheet->getCellByColumnAndRow(0, $i)->getValue();
$data2= $objWorksheet->getCellByColumnAndRow(1, $i)->getValue();
$data3= $objWorksheet->getCellByColumnAndRow(2, $i)->getValue();
//Todo: insert to db
}
If "by recipe" you mean by a calculation, then check the datatype of a cell rather than the value:
if ($objWorksheet->getCellByColumnAndRow(1, $i)->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) {
echo 'I contain a formula; use getCalculatedValue() to get my value';
}
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"];
}