I use PHPExcel to import data from a .csv file which has the same rows and columns with a excel file. Basically I open them with LibreOffice and they look the same. However there are two result when calculating theirs worksheet dimensions.
csv: A1:A10
xlsx: A1: AMK10
I just want to ask that it is always like that due to the different formats or I do something wrong?
$pi = pathinfo($filePath);
switch ($pi['extension']) {
case 'xls':
$reader = PHPExcel_IOFactory::createReader('Excel5');
break;
case 'xlsx':
$reader = PHPExcel_IOFactory::createReader('Excel2007');
break;
case 'csv':
$reader = PHPExcel_IOFactory::createReader('CSV');
break;
default:
return array();
}
$phpexcel = $reader->load($filePath);
$sheet = $phpexcel->getActiveSheet();
$sheet->calculateWorksheetDimension();
When loading a CSV file, if the delimiter isn't a default comma (,) then you need to explicitly set the delimiter for the reader. e.g.
PHPExcel_IOFactory::createReader('CSV');
$reader->setDelimiter(';');
Related
I have been trying to extract images and charts from an Xlsx file using the phpspreadsheet libray; I have however been unsuccessful.
Indeed, the piece of code I wrote is unable to find any image or chart from my xlsx file.
However, when I convert the file from Xlsx to Xls using Excel, the same code works and manages to extract images and charts.
This is the code i use to load my spreadsheet :
$fileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($filePath);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileType);
$spreadsheet = $reader->load($filePath);
And then I added the code provided by the official documentation :
$i = 0;
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG :
$extension = 'png';
break;
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
break;
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg';
break;
}
} else {
$zipReader = fopen($drawing->getPath(),'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader,1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
$myFileName = '00_Image_'.++$i.'.'.$extension;
file_put_contents($myFileName,$imageContents);
}
The above code works with an .xls file but not with an .xlsx : the getDrawingCollection and/or getChartCollection return an empty array with .xlsx files...
Do any of you guys know how to perform this?
I'm open to any solution... even if it means converting the file via another library...
Thanks in advance,
I found the solution... one line of code, to add after initializing the reader :
$reader->setIncludeCharts(true);
I wrote a php script that allows me to read an uploaded excel file and insert all the images contained in a folder by renaming them with the cell values "style" and "color" to have style_color.jpg. The script works fine but if I upload an xlsx file containing merged cells like this:
images with the same "style" doesn't work.The tool will just put the style on the first image. I would like the first two images to be called :
SCJEG4_1041
SCJEG4_0049
How can I read these merged cells?
<?php
//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_images.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xlsx);
//Unique name folder for the pictures
$dirname = uniqid();
mkdir("C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/");
//reading the xlsx file
$sheet = $objPHPExcel->getActiveSheet();
foreach ($sheet->getDrawingCollection() as $drawing ) {
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
$extension = 'png'; break;
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif'; break;
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg'; break;
}
} else {
$zipReader = fopen($drawing->getPath(),'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader,1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
$chemin = "C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/";
}
//retrieving cell values for the images name
$row = (int) substr($drawing->getCoordinates(), 1);
$stylecode = $sheet->getCell('H'.$row)->getValue();
$colorcode = $sheet->getCell('E'.$row)->getValue();
$finalname = $stylecode.'_'.$colorcode;
$myFileName = $chemin.$finalname.'.'.$extension;
file_put_contents($myFileName, $imageContents);
}
?>
If you can assume that you read the rows in sequence, you can get the cell value and if the cell is blank, use the previous value. This code use ?: to say if it's blank, use $stylecode ...
$stylecode = $sheet->getCell('H'.$row)->getValue() ?: $stylecode;
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"];
}
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.
I currently have a .xlsx file with a workbook with multiple sheets with text and images.
I need to import this data into my MySQL database.
Does anyone know of any tutorials or just some code that can help me get all the sheet within the workbook and retrieve text and images, and insert them into the database.
Check out PHPExcel. Here's how you would loop through the sheets. I'm not sure how you can get images though.
$reader = new PHPExcel_Reader_Excel2007();
$excel = $reader->load($filename);
foreach ($excel->getWorksheetIterator() as $worksheet){
// Get the data from current worksheet
// and store in DB as you like
}
$reader = new PHPExcel_Reader_Excel2007();
$PHPExcel = $reader->load('test.xlsx');
$worksheet = $PHPExcel->getActiveSheet();
// extract images from worksheet and save files: 0.jpeg, 1.jpeg, 2.png, ...
foreach ($worksheet->getDrawingCollection() as $i => $drawing) {
$filename = $drawing->getPath();
$imagesize = getimagesize($filename);
switch ($imagesize[2]) {
case 1:
$image = imagecreatefromgif($filename);
imagegif($image, "$i.gif");
break;
case 2:
$image = imagecreatefromjpeg($filename);
imagejpeg($image, "$i.jpeg");
break;
case 3:
$image = imagecreatefrompng($filename);
imagepng($image, "$i.png");
break;
default:
continue 2;
}
}