I am new to PHPExcel, first time I’ve used it. I have written this piece of code, but I know that there is a better, faster way. At the moment, when I read the sample spreadsheet (6000 rows, same as the actual spreadsheet) it takes around 2 minutes on localhost.
So, in addition to making the code faster and more streamlined, is there a way to show the actual progress?
I have read through the documentation, but still struggle with this.
Here is the code I’m currently using:
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../local_code/classes/');
/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';
/** Define a Read Filter class implementing PHPExcel_Reader_IReadFilter */
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// read columns A, C, G, H from row 2
if ($row >= 2) {
if (in_array($column,array("A","C","G","H"))) {
return true;
}
}
return false;
}
}
$inputFileName = 'newsheet.xlsx'; // change to uploaded file
$sheetname = 'FULL COMBINED';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly($sheetname);
$objReader->setReadFilter(new MyReadFilter());
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,false,false,true);
foreach($sheetData as $row => $columns) {
if($row != 1) {
$value = '';
foreach($columns as $cell => $val) {
if($cell == 'A') {
$val = trim($val);
}
if($cell == 'C') {
if(substr($val,0,1) != 'B') {
$val = trim($val);
$temp = substr($val,1);
if(is_numeric($temp))
$val = (int) $temp;
}
}
if($cell == 'G') {
$val = ($val * 86400) - 2209075200 - 86400;
}
if($cell == 'H') {
$val == floatval($val);
}
if($val != "")
$value[] = $val;
}
$values = "('" . implode("','",$value) . "')";
mysql_query("INSERT INTO projects_timesheet (employee_code,cost_code,date,hours) VALUES " . $values)or die(mysql_error());
}
}
Question 1
Is there a faster way of doing what I’m doing now? I know about chunking, but it seems I’m doing it wrong as it doesn’t work.
Question 2
Is there a way that I can show the user at what row the script currently is?
Any help will be appreciated
You have about 6k SQL inserts, try to insert all data by one SQL query.