Best way to validate uploaded Excel file data using PHPExcel - php

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;
}
}

Related

Import Excel Data to mysql 1 sheet only using PHP

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);
}
}

Not able to retrive data from array

I am trying to parse an Excel file. I am able to get the contents of individual cells of the excel. I am unable to add the data I got from the cell into an array.
function parseExcel($inputFileName){
$mh = new MainHandler;
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
}catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$Arr = array();
// Get worksheet dimensions
$sheet = $objPHPExcel->getActiveSheet();
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 1; $row <= $highestRow; $row++){
$myArray = array();
for($col = 'A' ; $col <= $highestColumn ; $col++){
$a = $sheet->getCell($col.$row);
// echo "\n".$a;
$myArray[] = $a;
}
// $Arr[] = $myArray;
echo json_encode($myArray);
}
// echo json_encode($Arr);
}
The output i get is
[{},{},{},{},{}][{},{},{},{},{}][{},{},{},{},{}]
What should be done to get the populated array as output?

PHPExcel - How can i read the Excel sheet row by row

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++;
}

PHPExcel error function getNamespaces() on a non-object

I am trying to parse excel files with help of PHPExcel library, here is my function for parsing tables
function readXLS($inputFileName) {
require_once(LIB_PATH.'PHPExcel.php');
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$arr_data = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$value=$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
$arr_data[$row-1][$col]=$value;
}
}
return $arr_data;
}
When i am parsing *.xlsx format all works good, but when i uploading for parsing *.xls format i have an error Call to a member function getNamespaces() on a non-object in <b>Z:\home\mysyte\www\trunk\UI\lib\PHPExcel\Reader\Excel2003XML.php

PHPExcel - Reading the Cells and Passing it into MYSQL

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);
}
}

Categories