PHPExcel - dynamically check columns in a row - php

I have a xlsx file where the first row has:
image :
I need to dynamically check how much locales are there (by column name), as it can happen that it can be only one or 5/6 columns.
How to set it?
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filePath);
$activeSheet = $phpExcelObject->getActiveSheet()->rangeToArray('B1:G1');
dump($activeSheet);die;

at first, you can use PhpSpreadsheet for loading Excel files.
there is example code for counting first row keys :
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
$reader = new \PhpOffice\PhpSpreadsheet\Reader\xlsx();
$spreadsheet = $reader->load($filePath);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
$firstRow = $sheetData[0];
$cnt = 0;
foreach ($firstRow as $value) {
if($value)
$cnt++;
}
//because of first column
$cnt--;
the last line, mines one is because of your first column "key"

Related

Generate .xlsx file using fromArray for a big amount of data

I need to write in a .xlsx file about 111.100 rows, using fromArray() but I have a strange error
I use phpspreadsheet library
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$columnLetter = 'A';
foreach ($columnNames as $columnName) {
// Allow to access AA column if needed and more
$sheet->setCellValue($columnLetter.'1', $columnName);
$columnLetter++;
}
$i = 2; // Beginning row for active sheet
$columnLetter = 'A';
foreach ($columnValues as $columnValue) {
$sheet->fromArray(array_values($columnValue), NULL, $columnLetter.$i);
$i++;
$columnLetter++;
}
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
// In this case, we want to write the file in the public directory
// e.g /var/www/project/public/my_first_excel_symfony4.xlsx
$excelFilepath = $directory . '/'.$filename.'.xlsx';
// Create the file
$writer->save($excelFilepath);
And I get the exception :
message: "Invalid cell coordinate AAAA18272"
#code: 0
#file: "./vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php"
Can you help me please ?
Excel pages are limited. The limit is huge but still limited. This is a correct filter so you can't write if there is no space for it.
Anyway you shouldnt use excel pages for such a big amount of data, you can try fragmenting it into smaller pieces, but databases should be the way to manipulate such amount of information

PHPSpreadsheet: how to get the number of loaded rows?

How do I find out how many rows I have loaded using PHPSpreadsheet\Reader\Xlsx::load() method?
I cannot find methods (or properties) for getting row count in Spreadsheet or Worksheet classes either.
BTW I am using following code:
$filename = 'test.xlsx';
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($filename);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$reader->setLoadSheetsOnly($sheet);
$this->spreadsheet = $reader->load($filename);
$this->worksheet = $this->spreadsheet->getActiveSheet();
Using the worksheet's getHighestRow() method
$highestRow = $this->spreadsheet->getActiveSheet()->getHighestRow();
or getHighestDataRow() if you're only interested in rows where cells contain data and not any blank rows at the end of the worksheet

Read excel sheet containing merged cells using PHPExcel

I want to read an excel sheet completely and using AJAX send each row to another page for processing. So I have used the following code for converting the excel sheet data into JSON array(Reference PHPExcel example provided in Library):
<?php
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Asia/Kolkata');
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel-1.8/Classes/');
require_once 'PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($fileLocation);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly("SHEETNAME");
$objPHPExcel = $objReader->load($fileLocation);
$data = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
?>
Here $filelocation is the location of the uploaded file which is to be read for sending the rows individually using AJAX to another page.
I am using $data in javascript as
DataToBeUploaded=<?php echo json_encode($data);?>;
But the excel sheet contains some merged cells so PHPExcel is not able to read the values in these merged cells. Hence values in these cells are read as NULL.
Is there a way where I can use the merged cells' upper left cell value for all of the subsequent cells? (Actually in my case cells are merged vertically only)
Eg.
I have (Assume rows are numbered from 1 and columns from A)
Here PHPExcel reads this as:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]=''
$data[2][B]='456'
$data[3][A]=''
$data[3][B]='789'
I want the snippet to result in these values:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]='abc'
$data[2][B]='456'
$data[3][A]='abc'
$data[3][B]='789'
Referring to https://github.com/PHPOffice/PHPExcel/issues/643
I have written the following snippet:
$referenceRow=array();
for ( $row = 2; $row <= $noOfBooks; $row++ ){
for ( $col = 0; $col < 7; $col++ ){
if (!$objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isInMergeRange() || $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isMergeRangeValueCell()) {
// Cell is not merged cell
$data[$row][$col] = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getCalculatedValue();
$referenceRow[$col]=$data[$row][$col];
//This will store the value of cell in $referenceRow so that if the next row is merged then it will use this value for the attribute
} else {
// Cell is part of a merge-range
$data[$row][$col]=$referenceRow[$col];
//The value stored for this column in $referenceRow in one of the previous iterations is the value of the merged cell
}
}
}
This will give the result exactly as required

Set images for price list via phpexcel

I have array of data like:
$products = array(
array('path/to/image1', 'name1', 'description1'),
array('path/to/image2', 'name2', 'description2'),
array('path/to/image3', 'name3', 'description3'),
...
array('path/to/imageN', 'nameN', 'descriptionN'),
);
With this code I generate *.xlsx table:
foreach($products as $row) {
$c = 0;
foreach ($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($c, $r, $cell);
$c++;
}
$r++;
}
require_once 'Classes/PHPExcel/IOFactory.php';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('/path/for/save');
And after that I get a table with path, name and descriptions. Please help me, because I can't get table where instead of pathes I will get images.
Setting a cell to contain 'path/to/image1' will do exactly that, set the cell to contain a string value of 'path/to/image1'.
You need to set images very specifically, as explained in the documentation and shown in the examples:
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Image');
$objDrawing->setPath('./path/to/image1.jpg');
$objDrawing->setCoordinates('B2');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
You should also note that MS Excel does not store images in a cell. It stores images overlaying a cell, so the image may cover several cells
EDIT
If you need to convert numeric coordinates such as $row=3 and $col=0 to a cell reference like A3:
$cellReference = PHPExcel_Cell::stringFromColumnIndex($col) . $row;
or
$cellReference = $objPHPExcel->getActiveSheet()
->getCellByColumnAndRow($col, $row)
->getCoordinate();

PHPExcel. How to check if current cell is merged with another?

I use PHPExcel to import Excel files to my site. For example, there is two cells, A1 and A2, both merged. Is there a way to to find out is A1 merged to another cell (A2 or other) or not?
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->mergeCells('A1:E1');
$cell = $sheet->getCell('A1');
// Check if cell is merged
foreach ($sheet->getMergeCells() as $cells) {
if ($cell->isInRange($cells)) {
echo 'Cell is merged!'
break;
}
}
I think there isn't better solution because of the way phpexcel stores information about merged cells.
The easiest way is to use the getMergeRange() method.
if ($cell->getMergeRange()) {
// cell is merged
}
I suspect many people will want to know the value of the merged cell, in which case you can refer to the following code:
if (($range = $cell->getMergeRange()) && !$cell->isMergeRangeValueCell()) {
$first_in_range_coordinates = strtok($range, ':');
$value = $sheet->getCell($first_in_range_coordinates)->getValue();
}

Categories