PHPExcel, select sheet when importing data to mysql
I want to import data from a sheet but from sheet 2 and I'm not getting it. I indicated sheet 2 (index 1) as active in this way, but always enters sheet 1 (index 0):
$objWorksheet = OBJ objPHPExcel- > setActiveSheetIndex(1);
What will be incorrect?
This is the code I'm using:
Working SCRIPT for importing xlsx by choosing tab (INDEX)
<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('America/Sao_Paulo');
if (PHP_SAPI == 'cli')
die('This example should only be run from a Web Browser');
/** Include PHPExcel and MySQLi db */
require_once dirname(__FILE__) . '/Classes/DB.php';
require_once dirname(__FILE__) . '/Classes/PHPExcel.php';
//Create DB object
use DB\MySQLi;
// Create new PHPExcel object
$objPHPExcel = PHPExcel_IOFactory::load("arquivo.xlsx");
$objWorksheet = $objPHPExcel->getSheet(1); // aqui indica a aba que quer importar
$dataArr = array();
foreach ($objWorksheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(True); //varre todas as células
foreach ($cellIterator as $cell) {
$colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
echo ('Linha: '.$rowIndex.' Coluna: '.$colIndex.' Valor: '.$cell->getValue());
$val = $cell->getValue();
$dataArr[$rowIndex][$colIndex] = $val;
}
}
unset($dataArr[1]);
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'dbase';
$db = new MySQLi($hostname, $username, $password, $database);
foreach($dataArr as $val){
$query = $db->query("INSERT INTO employees SET fname = '" . $db->escape($val['1']) . "', lname = '" . $db->escape($val['2']) . "', email = '" . $db->escape($val['3']) . "', phone = '" . $db->escape($val['4']) . "', company = '" . $db->escape($val['5']) . "'");
}
1
Author: Nelson Aguiar, 2016-05-24
1 answers
To work on tabs or sheets, as you prefer, you should use, remembering that the indexing of the tabs start at 0:
$objWorksheet = $objPHPExcel->getSheet(1);
Or alternatively but less productive as I said in my comment;
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
And then take the data like this:
$worksheetTitle = $worksheet->getActiveSheet->getTitle();
Or:
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1).getActiveSheet();
Try to do this way in foreach:
foreach ($objWorksheet->getRowIterator() as $row) {
$rowIndex = $row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(True); //varre todas as células
foreach ($cellIterator as $cell) {
$colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
echo ('Linha: '.$rowIndex.'Coluna: '.$colIndex.'Valor: '.$cell->getValue());
}
}
Reference: PHPExcel Developer Documentation Worksheets
Hope it helps.
1
Author: Nelson Aguiar, 2016-05-24 15:52:26