How can i read Excel worksheet row by row using PHPExcel? I have a sheet contains more than 100000 rows, but i want to read only 500 rows.
$sheetData = $objPHPExcel->getActiveSheet();
$highestRow = $sheetData->getHighestRow();
$highestColumn = $sheetData->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table>';
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>';
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $sheetData->getCellByColumnAndRow($col, $row)->getValue() . '</td>';
}
echo '</tr>';
}
echo '</table>';
If you only want to read 500 rows, then only load 500 rows using a read filter:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example2.xls';
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class myReadFilter implements PHPExcel_Reader_IReadFilter
{
private $_startRow = 0;
private $_endRow = 0;
/** Set the list of rows that we want to read */
public function setRows($startRow, $chunksize) {
$this->_startRow = $startRow;
$this->_endRow = $startRow + $chunkSize;
}
public function readCell($column, $row, $worksheetName = '') {
// Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
if (($row >= $this->_startRow && $row < $this->_endRow)) {
return true;
}
return false;
}
}
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Define how many rows we want to read for each "chunk" **/
$chunkSize = 500;
/** Create a new Instance of our Read Filter **/
$chunkFilter = new myReadFilter();
/** Tell the Reader that we want to use the Read Filter that we've Instantiated **/
$objReader->setReadFilter($chunkFilter);
/** Tell the Read Filter, the limits on which rows we want to read this iteration **/
$chunkFilter->setRows(1,500);
/** Load only the rows that match our filter from $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
See the PHPExcel User Documentation - Reading Spreadsheet Files document in /Documentation for more details on Read Filters
You can load 500 rows or even setting start index by setting parameters directly to the getRowIterator function.
$path = "Your File Path HERE";
$fileObj = \PHPExcel_IOFactory::load( $path );
$sheetObj = $fileObj->getActiveSheet();
$startFrom = 50; //default value is 1
$limit = 550; //default value is null
foreach( $sheetObj->getRowIterator($startFrom, $limit) as $row ){
foreach( $row->getCellIterator() as $cell ){
$value = $cell->getCalculatedValue();
}
}
This loops through all rows and columns and assigns the cell value to $cellValue. If the $i is greater than 500, it breaks out the loop
$objWorksheet = $objPHPExcel->getActiveSheet();
$i = 0;
foreach ($objWorksheet->getRowIterator() as $row) {
if ($i > 500) break;
$i++;
foreach ($row->getCellIterator() as $cell) {
$cellValue = trim($cell->getCalculatedValue());
}
}
require_once "/PATH TO PHP EXCEL FOLDER/PHPExcel.php";
$inputFileName = $_FILES['FILENAME'];
$objTpl = PHPExcel_IOFactory::load('./PATH TO UPLOAD FOLDER/' . $inputFileName);
$sheetData = $objTpl->getActiveSheet()->toArray(null, true, true, true);
array_shift($sheetData);
$i=0;
$test_array = array();
foreach($sheetData as $key=>$val){
if($i < 500)
$test_array[$i] = $val;
$i++;
}
Related
I am trying to import a grade sheet into mysql database but that excel file have multiple sheet how can i make it so only a specified sheet will be going into my database
$uploadfile=$_FILES['uploadfile']['tmp_name'];
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
foreach($objExcel->getWorksheetIterator() as $worksheet)
{
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}
}
As far as I understand you are looking to get data from a specific sheet.
In PHPExcel there is this function: setActiveSheetIndex(sheet_index)
You can try like this:
$uploadfile = 'test.xlsx';
$objExcel = PHPExcel_IOFactory::load($uploadfile);
$objData = PHPExcel_IOFactory::createReader('Excel2007');
//read only
$objData->setReadDataOnly(true);
$objPHPExcel = $objData->load($uploadfile);
// Select sheet to get
$sheet = $objPHPExcel->setActiveSheetIndex(1);
$Totalrow = $sheet->getHighestRow();
$LastColumn = $sheet->getHighestColumn();
$TotalCol = PHPExcel_Cell::columnIndexFromString($LastColumn);
$data = [];
// Proceed to loop through each data cell
// Repeat rows, Since the first row is assumed to be the column header, we will loop the value from line 2
for ($i = 2; $i <= $Totalrow; $i++) {
//---- Loop column
for ($j = 0; $j < $TotalCol; $j++) {
// Proceed to get the value of each cell into the array
$data[$i - 2][$j] = $sheet->getCellByColumnAndRow($j, $i)->getValue();;
}
}
var_dump($data);
i just deleted the foreach and add getSheetName()
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
$worksheet = $objExcel->getSheetByName('GEN.AVERAGE');
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}
I'm working on phpexcel. The File I'm working on is from tally export file. I have to read this file and save the data to each user .
For example from this file I need only A2:G10 as HTML/TABLE. So i can display to the particular member (Adv. Chandra Mogan) individually.
I NEED A TABLE FOR ONLY A PORTION OF THE SHEET
What I have done so far:
protected function doExcelUpdate() {
$inputFileName = $this->getParameter('temp_directory') . '/file.xls';
if (!file_exists($inputFileName)) {
$this->addFlash('sonata_flash_error', 'File: not found in temp directory');
return;
}
$this->addFlash('sonata_flash_info', 'File: exist');
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
$this->addFlash('sonata_flash_error', 'Error in PHPExcel');
return;
}
$sheet = $objPHPExcel->getSheet(0);
if (!$sheet) {
$this->addFlash('sonata_flash_error', 'Error in reading sheet');
return;
}
$objPHPExcel->getSheet(0)
->getStyle('A1:G10')
->getProtection()
->setLocked(
PHPExcel_Style_Protection::PROTECTION_PROTECTED
);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->setSheetIndex(0);
$objWriter->save($this->getParameter('temp_directory') . '/output.html');
}
A1:G10 is not locked. Entire sheet is printed.
First point: "Locking" doesn't change the sheet size, or set a "view window"; it protects parts of the sheet from being edited.
Second point: "Locking" is a feature of Excel, and supported for excel writers, but not for HTML.
Third point: there is no direct mechanism to write only part of a worksheet.
As a suggestion, you might create a new blank worksheet, and then copy the data/style information from the cell range that you want in your your main worksheet to that new worksheet starting from cell A1; then send that worksheet to the HTML Writer.
You can't achive this using locked or hidden cells when you use HTML writer.
You can use a workaround creating a new worksheet and after adding the portion you want to display.
For mantain style on new worksheet (like font, color, border) you must extract it for each cell from the orginal worksheet and apply to the copied cells.
The same thing is for merged cells in the old worksheet.
Your function doExcelUpdate() should be like this:
protected function doExcelUpdate()
{
$inputFileName = $this->getParameter('temp_directory').'/file.xls';
if (!file_exists($inputFileName)) {
$this->addFlash('sonata_flash_error', 'File: not found in temp directory');
return;
}
$this->addFlash('sonata_flash_info', 'File: exist');
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$originalPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
$this->addFlash('sonata_flash_error', 'Error in PHPExcel');
return;
}
$originalSheet = $originalPHPExcel->getSheet(0);
if (!$sheet) {
$this->addFlash('sonata_flash_error', 'Error in reading sheet');
return;
}
// Get the data of portion you want to output
$data = $originalSheet->rangeToArray('A1:G11');
$newPHPExcel = new PHPExcel;
$newPHPExcel->setActiveSheetIndex(0);
$newSheet = $newPHPExcel->getActiveSheet();
$newSheet->fromArray($data);
// Duplicate style for each cell from original sheet to the new sheet
for ($i = 1; $i < 11; $i++) {
for ($j = 0; $j <= 6; $j++) {
$style = $originalSheet->getStyleByColumnAndRow($j, $i);
$newSheet->duplicateStyle($style, PHPExcel_Cell::stringFromColumnIndex($j).(string)$i);
}
}
// Merge the same cells that are merged in the original sheet
foreach ($originalSheet->getMergeCells() as $cells) {
$inRange = false;
foreach (explode(':', $cells) as $cell) {
$inRange = $originalSheet->getCell($cell)->isInRange('A1:G11');
}
// Merge only if in range of the portion of file you want to output
if ($inRange) {
$newSheet->mergeCells($cells);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($newPHPExcel, 'HTML');
$objWriter->save($this->getParameter('temp_directory').'/output.html');
}
UP TO NOW FOR THE WORK TO BE COMPLETED, I HAVE DONE THIS,
private function doExcelUpdate() {
$inputFileName = $this->getParameter('temp_directory') . '/file.xls';
$synopsis = PHPExcel_IOFactory::load($inputFileName)->getSheet(0);
$column = $synopsis->getHighestColumn();
$row = $synopsis->getHighestRow();
$this->cleanUserPayment();
$this->doExcelUpdateTable($synopsis, $column, $row);
$this->deleteExcelFile();
}
private function cleanUserPayment() {
$em = $this->getDoctrine()->getManager();
$classMetaData = $em->getClassMetadata('AppBundle\Entity\UserPayment');
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->beginTransaction();
try {
$connection->query('SET FOREIGN_KEY_CHECKS=0');
$q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
$connection->executeUpdate($q);
$connection->query('SET FOREIGN_KEY_CHECKS=1');
$connection->commit();
} catch (\Exception $e) {
$connection->rollback();
}
}
private function doExcelUpdateTable($synopsis, $column, $row) {
set_time_limit(300);
$t = [];
for ($r = 1; $r <= $row; $r++) {
for ($c = "A"; $c <= $column; $c++) {
$cell = $synopsis->getCell($c . $r)->getFormattedValue();
if ($cell == 'Ledger:') {
$t[] = $r;
}
}
}
$t[] = $row+1;
$numItems = count($t);
$i = 0;
$em = $this->getDoctrine()->getManager();
foreach ($t as $key => $value) {
if (++$i != $numItems) {
$up = new UserPayment();
$up->setName($synopsis->getCell('B' . $value)->getFormattedValue());
$up->setMessage($this->doExcelUpdateTableCreate($synopsis, $column, $value, $t[$key + 1]));
$em->persist($up);
// $this->addFlash('sonata_flash_error', 'Output: ' . $synopsis->getCell('B' . $value)->getFormattedValue() . $this->doExcelUpdateTableCreate($synopsis, $column, $value, $t[$key + 1]));
}
}
$em->flush();
$this->addFlash('sonata_flash_success', "Successfully updated user bills. Total data updated::" . count($t));
}
private function doExcelUpdateTableCreate($synopsis, $column, $rowS, $rowE) {
$mr = NULL;
$x = 0;
$alphas = range('A', $column);
$oneTable = '<table border="1">';
for ($r = $rowS; $r < $rowE; $r++) {
$oneTable .= "<tr>";
for ($c = "A"; $c <= $column; $c++) {
if ($x > 0) {
$x--;
continue;
}
$mr = NULL;
$x = 0;
$cell = $synopsis->getCell($c . $r);
$cellVal = $cell->getFormattedValue();
if ($cellVal == NULL) {
$cellVal = " ";
}
$cellRange = $cell->getMergeRange();
if ($cellRange) {
$mr = substr($cellRange, strpos($cellRange, ":") + 1, 1);
$upto = array_search($mr, $alphas);
$x = ($upto - array_search($c, $alphas));
$oneTable .= "<td colspan=" . ($x + 1) . " style='text-align:right;'>" . $cellVal . "</td>";
} else {
$oneTable .= "<td>" . $cellVal . "</td>";
}
}
$oneTable .= "</tr>";
}
$oneTable .= "</table>";
return $oneTable;
}
private function deleteExcelFile() {
$filesystem = new \Symfony\Component\Filesystem\Filesystem();
$filesystem->remove($this->getParameter('temp_directory') . '/file.xls');
}
What would be the most efficient way of checking data contained in arrays
I want to validate in the following ways:
if cell a and b are a string
if cell c and d are numbers
if cells are empty
Then how would it be best to catch errors and display them to the user?
I'm using codeigniter and the PHPExcel library
an example of where I'm currently at
public function read_excel()
{
$this->load->library('excel');
$inputFileName = 'test.xlsx';
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet
for ($row = 2; $row <= $highestRow; $row++){ // Read a row of data into an array
$rowData = $sheet->rangeToArray('A'.$row.':'.$highestColumn.$row,NULL,TRUE,FALSE);
$cella = strtoupper($rowData[0][0]);
$cellb = strtoupper($rowData[0][1]);
$cellc = $rowData[0][2];
$celld = $rowData[0][3];
}
}
To Answer my own question i eventually went with the below
if (!isset($rowData[0][0],$rowData[0][1],$rowData[0][2])) {
echo "error cells a-c are required.";
}
for ($i=0; $i <$columns ; $i++) {
switch ($rowData[0][$i]) {
case (is_numeric($rowData[0][$i])):
filter_var($rowData[0][$i],FILTER_SANITIZE_NUMBER_INT);
echo $rowData[0][$i];
echo "</br>";
break;
case (is_string($rowData[0][$i])):
$rowData[0][$i] = preg_replace("/[^A-Za-z0-9\-]/"," ",$rowData[0][$i]);
break;
}
}
I have a excel file which contains certain rows with color i want to get the row id of a particular color code but unable to do it .. already searched but found nothing below is my code for PHPEXCEL
$cellColor = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
This will give me the color code and for the value i have $cell->getValue() where $cell is some variable for $cellIterator
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell)
{
$cellColor = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
if (!empty($cell->getCalculatedValue())) {
if ($cellColor == 'yellow') {
echo ($cellColor.'======'.$cell->getValue());
}
}
}
}
$cell->getValue() will give me the value of that particular color code But, the problem is if i have 2 rows with color yellow then $cell->getValue() will give two value like 0-> yellow1 1-> yellow2 but after deleting the 1st yellow colour data in excel then result will be 0-> yellow2 which is wrong what i need is 0->'' 1-> yellow2 Thats why i need row id for that particular color so that i can identify the row.
After hours of practicing got my expected result
$objPHPExcel = PHPExcel_IOFactory::load('someFile.xls');
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
//$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
//$nrColumns = ord($highestColumn) - 64;
$groupCount = array();
$standardSetCount = array();
$standardCount = array();
$learningTargetCount = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col < $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$colorCode = $objPHPExcel->getActiveSheet()->getStyle($cell->getCoordinate())->getFill()->getStartColor()->getRGB();
/*
* Yellow
*/
if ($colorCode == 'FFFF00') {
$val = $cell->getValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
$groupCount[] = $val; // $groupCount[] = $dataType;
}
/*
* gold
*/
if ($colorCode == 'CC9900') {
$val = $cell->getValue();
$standardSetCount[] = $val;
}
/*
* red
*/
if ($colorCode == 'FF3333') {
$val = $cell->getValue();
$standardCount[] = $val;
}
/*
* green
*/
if ($colorCode == '00CC33') {
$val = $cell->getValue();
$learningTargetCount[] = $val;
}
}
}
$group = (array_chunk($groupCount, $highestColumnIndex));
$standardSet = (array_chunk($standardSetCount, $highestColumnIndex));
$standard = (array_chunk($standardCount, $highestColumnIndex));
$learningTarget = (array_chunk($learningTargetCount, $highestColumnIndex));
echo '<pre>';
print_r($learningTarget);
}
I'm trying to use a php script to read an xlsx file, and pass the information from the cells off into MYSQL
here is my code, I'm using PHPExcel version 1.7.6 and PHP 5.3.5
require_once 'PHPExcel.php';
$inputFileType = 'Excel2007';
$inputFileName = $upload_path . $filename;
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class chunkReadFilter implements PHPExcel_Reader_IReadFilter
{
private $_startRow = 0;
private $_endRow = 0;
/** Set the list of rows that we want to read */
public function setRows($startRow, $chunkSize) {
$this->_startRow = $startRow;
$this->_endRow = $startRow + $chunkSize;
}
public function readCell($column, $row, $worksheetName = '') {
// Only read the heading row, and the configured rows
if (($row == 1) ||
($row >= $this->_startRow && $row < $this->_endRow)) {
return true;
}
return false;
}
}
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Define how many rows we want to read for each "chunk" **/
$chunkSize = 2048;
/** Create a new Instance of our Read Filter **/
$chunkFilter = new chunkReadFilter();
/** Tell the Reader that we want to use the Read Filter **/
$objReader->setReadFilter($chunkFilter);
/** Loop to read our worksheet in "chunk size" blocks **/
for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
/** Tell the Read Filter which rows we want this iteration **/
$chunkFilter->setRows($startRow,$chunkSize);
/** Load only the rows that match our filter **/
$objPHPExcel = $objReader->load($inputFileName);
// Need to pass the cell values into the variables
This is where I need to use something like this
for ($x = 2; $x < = count($data->sheets[0]["cells"]); $x++) {
$item_number = $data->sheets[0]["cells"][$x][1];
$qty_sold = $data->sheets[0]["cells"][$x][2];
$cost_home = $data->sheets[0]["cells"][$x][3];
which would work for phpexcelreader, but I just dont know which functions would do the same for phpExcel
//here is where I would pass those values into MYSQL
$sql = "INSERT INTO sales_report (`item_number`,`qty_sold`, `cost_home`)
VALUES ('$item_number',$qty_sold,'$cost_home')";
echo $sql."\n";
mysql_query($sql);
}
?>
I'm at a total loss as how to get the data from the spreadsheet into mysql
EDIT:
I've managed to get the data printed by using the following arrays
foreach ($objWorksheet->getRowIterator() as $row) {
$j = 1;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell) {
$data->sheets[0]['cells'][$i][$j] = $cell->getValue();
$j++;
} // end cell getter
$i++;
} // end row getter
But I just can't seem to get it to insert into my table. I have tried using the implode function as well but nothing happens.
The easiest way to do this is to convert xlsx to csv file on the fly, and than use normal CSV parsing. Just instantiate CSVWriter and save to a temporary location (I can provide example code by tomorrow)
Sample code:
$objReader = PHPExcel_IOFactory::load ( $file_path );
$writer = PHPExcel_IOFactory::createWriter ( $objReader, 'CSV' );
$writer->save ( $csv_path );
if (($handle = fopen ( $csv_path, "r" )) !== false) {
while ( ($data = fgetcsv ( $handle)) !== false ) {
print_r($data);
}
}