For a school project, I have to collect data from an Excel file uploaded by the user. I am using Symfony2 and have installed a bundle I found on knpbundles, named ExcelBundle. I read that to collect data with it from an Excel file, I should use the createWriter method of my phpExcel object. That is what I have done as shown below.
public function addContactsFromExcelAction(Request $request) {
$uploadDir = '/var/www'.$request->getBasePath().'/uploads/';
//die(var_dump($uploadDir));
$file = $request->files->get('fichierExcel');
$fileName = $file->getClientOriginalName();
$fileSaved = $file->move($uploadDir,$fileName);
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($uploadDir.$fileName);
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');
}
But the thing is that actually, I do not really know how to use the writer to collect data from the cells of my excel datasheets.
Please, could anyone give me the trick to achieve my goal ?
You can iterate as this Example:
public function xlsAction()
{
$filenames = "your-file-name";
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);
foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
echo 'Worksheet - ' , $worksheet->getTitle();
foreach ($worksheet->getRowIterator() as $row) {
echo ' Row number - ' , $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo ' Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
}
}
}
}
}
More samples here
Related
Using PhpSpreadsheet,
when I read data from the xls table, I need to find out whether this cell is merged with others,
if yes, then do certain actions with it, if not, then do nothing
at the moment I thought of only checking for the presence of empty array elements after the text cell, but this solution is not quite universal ...
...
$inputFileName = $_FILES['uploadfile']["tmp_name"];
echo 'TMP-FILE-NAME: ' . $inputFileName;
$spreadsheet = IOFactory::load($inputFileName); //create new speedsheen object
$loadedSheetNames = $spreadsheet->getSheetNames(); //get name of Sheet
//and than print it
//get Sheet Name
foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$sheet = $spreadsheet->getSheet($sheetIndex);
echo "<table border=\"1\">";
$rows = $sheet->toArray();
**$mergeCell = $sheet->getMergeCells(); // - This is the answer to my question**
foreach ($rows AS $row) {
echo "<tr>";
foreach ($row AS $cell) {
echo "<td>" . $cell . "</td>";
}
}
echo '<br/>';
}
echo "</table>";
In order to check the cell was merged or not
First, you can use getMergeCells function to get all merged cells.
Then do loop in that cells list to check your cell is in or is not in that list.
Summarize: You can use this function to check cell merged or not
// Check cell is merged or not
function checkMergedCell($sheet, $cell){
foreach ($sheet->getMergeCells() as $cells) {
if ($cell->isInRange($cells)) {
// Cell is merged!
return true;
}
}
return false;
}
The code was referenced from this answer
For PhpSpreadSheet:
getMergeCells: https://phpoffice.github.io/PhpSpreadsheet/1.2.0/PhpOffice/PhpSpreadsheet/Worksheet/Worksheet.html#method_getMergeCells
isInRange: https://phpoffice.github.io/PhpSpreadsheet/1.2.0/PhpOffice/PhpSpreadsheet/Cell/Cell.html#method_isInRange
I am trying to read an excel file that has 03/05/2008 kind of format, but when I read using PhpSpreadsheet, it returns me 2008.0.
Is there a way to get the raw string format of columns instead of converting to float?
try {
$inputFileType = IOFactory::identify($path);
try {
$reader = IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$valuesSpreadsheet = $reader->load($path);
try {
$spreadsheetArr = $valuesSpreadsheet->getActiveSheet()->toArray();
dd($spreadsheetArr);
}
}
}
Edit: I don't want to get a specific cell and convert it to timestamp like the comments below. I want to get as array ->toArray() but getting all raw string formats.
Take out the $reader->setReadDataOnly(true) line prior to loading the data and the values should be displayed properly. If not you can also try the following code.
$path = 'yourPath';
try {
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($path);
try {
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$valuesSpreadsheet = $reader->load($path);
try {
$spreadsheetArr = $valuesSpreadsheet->getActiveSheet()->toArray(null, null, true, true);
print '<pre>' . print_r($spreadsheetArr, 1) . '</pre>';
} catch (Exception $e) {
echo $e . PHP_EOL;
}
} catch (Exception $e) {
echo 'Unable to load file ' . $path . PHP_EOL;
echo $e . PHP_EOL;
}
} catch (Exception $e) {
echo 'Unable to locate file ' . $path . PHP_EOL;
echo $e . PHP_EOL;
}
toArray() has a parameter to return the cell values formatted as they are in the spreadsheet. Try calling it like this:
$spreadsheetArr = $valuesSpreadsheet->getActiveSheet()->toArray(null, true, true, true);
About 80% of the way down this page is documentation for the toArray() function.
In short, toArray() can accept 4 parameters:
whatever value you want empty cells to return
(boolean) do formulas need to be calculated?
(boolean) does cell formatting matter?
(boolean) do you want the array indexed by the spreadsheet's column and row?
You should use getRowIterator() and getCellIterator() functions to loop through all cells. In the code below, all cells will be returned as raw values.
try {
$inputFileType = IOFactory::identify($path);
try {
$reader = IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path);
$worksheet = $spreadsheet->getActiveSheet();\
foreach ($worksheet->getRowIterator() as $index => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); //This loops through all cells
$cells = [];
foreach ($cellIterator as $cell) {
$cells[] = $cell->getValue();
}
$rows[] = $cells;
print_r($rows);
}
}
}
I am trying to parse an excel spreadsheet using phpexcel library in php but I can't get the logic correct for comparing a value in the cell.
I am using following code to read values in excel:
$sheet->getCellByColumnAndRow("10", $row)->getValue()
The HTML output is
☑
And when I try to find all the rows with this value using the following logic I never get the equation true.
for ($row = 5; $row <= $highestRow; ++$row) {
if ($sheet->getCellByColumnAndRow("10", $row)->getValue() == '☑') {
echo 'rowno ' . $row . ' ' . 'BOOKED';
echo '<br/>';
}else{
echo strtolower($sheet->getCellByColumnAndRow("10", $row)->getValue()) ;
echo '<br/>';
}
}
Could someone please let me know what I am doing incorrectly here?
In the PHP Developer Documentation, which I found through Google, they use Row- and Celliterators as follows:
$objWorksheet = $objPHPExcel->getActiveSheet();
foreach ($objWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $cell) {
$cell->getValue();
}
}
Using this you could use the following to compare it with the wanted value:
$check = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(10, $row)->getValue();
foreach ($objWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $cell) {
$value = $cell->getValue();
if($check == $value){
//what you want to happen, if it is true
} else {
//what you want to happen, if it is false
}
}
}
Discovered the value in the excel column is quoted_printable. I found out this by using following code:
foreach(mb_list_encodings() as $chr){
echo 'Row '. $row .'-'. mb_convert_encoding($var2, 'UTF-8', $chr)." : ".$chr."<br>";
}
this displays what encoding is for the value. My case was Quoted-Printable I found the solution here to encode quoted printable characters.
[
$objWorksheet = $objPHPExcel->getActiveSheet();
foreach ($objWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
if($cell->getRow()==1||$cell->getColumn()=='A'){
continue;
}
else{
$cell->$_column;
}
}
}][1]
Problem :
I need to get the values of $cell so that I can put it in a MySQL database , if there a good reference to get the methods of cell object?
There are libraries that make the cells of a xls file into an array and then manipulate and to store in a database to automate processes.
phpexcelreader
example of this would
<?php
require_once 'reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->read('archivoxls');
$celdas = $data->sheets[0]['cells']; // obtains cells of file xls
foreach ($celdas as $val) { // print cells
print_r($val);
echo "<br/>";
}
I know, there are lot's of questions here sbout improving PHPExcel performance. But all of them are about writing data, and my problem is in reading.
My function:
function parse($filename){
$objPHPExcel = PHPExcel_IOFactory::load($filename);
$activeSheet = $objPHPExcel->getActiveSheet();
$parsedData = array();
$columnHeaders = array('order', 'ts', 'summ', 'name', 'quant', 'price', 'bccu');
foreach ($activeSheet->getRowIterator() as $rkey => $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $ckey => $cell) {
$parsedData[$columnHeaders[$ckey]] = $cell->getCalculatedValue();
}
}
return $parsedData;
}
The file contains ~300 rows and 7 columns. And this script fails to run in 30 seconds.
How can i improve it?
edit:
used
$objReader = PHPExcel_IOFactory::createReader("Excel2007");
$objPHPExcel = $objReader->load($filename);
whth no success
If your columns are already defined, what about remove the column iterator?
Try something like this:
foreach ($activeSheet->getRowIterator() as $rkey => $row) {
$rowIndex = $row->getRowIndex ();
$parsedData[$rowIndex]['order'] = $activeSheet->getCell('A' . $rowIndex);
$parsedData[$rowIndex]['ts'] = $activeSheet->getCell('B' . $rowIndex);
$parsedData[$rowIndex]['summ'] = $activeSheet->getCell('C' . $rowIndex);
.
.
.
}
Try disabling the garbage collector before running parse() by issuing gc_disable(). Guessing that levels of iterations here don't get optimized properly by PHP.
If you're not going to change the file's contents; setting the reader to read-only gives about 10x boost.
For example:
$objReader = PHPExcel_IOFactory::createReader( 'Excel5' );
$objReader->setReadDataOnly( true );