PHPExcel find last row of data starting from a specific cell - php

i have a php script that read data from excel file starting from cell B6. However. I would like the php to be able to read data from B6 until the last row of data which in this case is cell D7.
I try searching online for answer and all i get is this $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
Can anyone help?
Below is my php script code:
require_once 'Classes/PHPExcel.php';
$path = 'import/Attachment F - Visitor or Supplier Request Template.xlsx';
$reader = PHPExcel_IOFactory::createReaderForFile($path);
$excel_obj = $reader->load($path);
$worksheet = $excel_obj->getSheet('0');
for($row=6;$row<=14;$row++){
$category = $worksheet->getCell('B'.$row)->getValue();
if($category!=''){
$uen = $worksheet->getCell('C'.$row)->getValue();
$company = $worksheet->getCell('D'.$row)->getValue();
echo $category." ".$uen." ".$company."<br/>";
}
}

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

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

PHPExcel - reading row comments , text strike missing

Am trying to read excel file with PHPExcel library
https://github.com/PHPOffice/PHPExcel
however when i read row then am not able to get comments on field and strikes on text also missing .
my code is
include 'PHPExcel/IOFactory.php';
$ftype = 'Excel2007';
$fname = 'data.xlsx';
$objexcel = PHPExcel_IOFactory::load($fname);
$sdata = $objexcel->getActiveSheet()->toArray(null,true,true,true);
foreach ($sdata as $k=>$d) {
print_r($d); // output
}
so it output comments and strikes which are in data.xlsx file are missing .
any idea how to display and check if row have comments and strikes through text

convert an EXCEL file to CSV file in PHP [duplicate]

This question already has answers here:
How to convert Excel XLS to CSV using PHP
(5 answers)
Closed 7 years ago.
I want to convert Excel files (.xls) into CSV file (.csv) with a script PHP ?
I tried many codes but it didn't work like this one !
No errors appear but it wont work Any idea or any other lines of codes that I can try ?
<?php
echo("it works");
require_once '../batchs/Classes/PHPExcel/IOFactory.php';
$inputFileType = 'Excel5';
$inputFileName = '../public/aixstream/stock.xls';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objWriter->setSheetIndex($sheetIndex);
$objWriter->save($loadedSheetName.'.csv');
}
?>
Thank you
As already stated in this answer, you can use the PHP-ExcelReader function to read the xls file. After that, you may easily convert it into CSV (or any other other format) using the following code, also available here.
Reading the xls file
//You will obviously need to import the function
//by downloading the file from the link above.
$reader=new Spreadsheet_Excel_Reader(); //Instantiate the function
$reader->setUTFEncoder('iconv'); // Set Encoder
$reader->setOutputEncoding('UTF-8'); // Set Output Encoding Type
$reader->read($filename); // Read the xls file
Data Output
/***
* Information about sheets is stored in boundsheets variable.
* This code displays each sheet's name.
***/
foreach ($reader->boundsheets as $k=>$sheet) //Run loop for all sheets in the file
{
echo "\n$k: $sheet";
}
//Now just save the data in the array as csv
/***
* Data of the sheets is stored in sheets variable.
* For every sheet, a two dimensional array holding table is created.
* This code saves all data to CSV file.
***/
foreach($reader->sheets as $k=>$data) // Run loop for all items.
{
echo "\n\n ".$reader->boundsheets[$k]."\n\n"; //Print Title
foreach($data['cells'] as $row) // Loop for all items
{
foreach($row as $cell) // Loop for every cell
{
echo "$cell".","; //Add a comma after each value
}
}
}
//It works! :D

Get named ranges in PHPExcel

Using PHPExcel, I would like to loop through all the named ranges in a workbook and then create a new tab for each one.
I am currently doing this in excel with a macro, like so:
Dim sheetName As String
sheetName = ActiveSheet.Name
Dim nName As Name
For Each nName In Names
If InStr(1, nName.RefersTo, sheetName) > 0 Then
Application.Goto Reference:=nName.Name
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = nName.Name
Selection.PasteSpecial Paste:=xlPasteValues
End If
Next nName
mystring = Sheets(1).Name
ActiveWorkbook.SaveCopyAs Filename:="P:\DP\CWBI\" & mystring & "_parsed.xls"
I can loop through active sheets in PHPExcel and dump them into an array for processing, like this:
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$sheets = $objReader->listWorksheetNames($file);
print_r ($sheets);
Does anyone know if it's possible to loop through all the named ranges?
Edit:
I'm trying the first suggestion below, but not getting any output. Here's the code:
$file="span_test.xlsx";
$objPHPExcel = PHPExcel_IOFactory::load($file);
foreach($objPHPExcel->getNamedRanges() as $name => $namedRange) {
echo $namedRange . "</br>";
}
Got it working now, my mistake in trying to echo an object. should be
print_r($name)
You have to actually load the workbook to access the named ranges
foreach($objPHPExcel->getNamedRanges() as $name => $namedRange) { ... }
which returns a PHPExcel_NamedRange object for each named range

Categories