Just started working with phpspreadsheet. I am trying to figure out how to skip the header row in my excel file when uploading.
require '../vendor/autoload.php';
if (pathinfo($_FILES['upexcel']['name'], PATHINFO_EXTENSION) == 'csv') {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
} else {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}
$spreadsheet = $reader->load($_FILES['upexcel']['tmp_name']);
$worksheet = $spreadsheet->getActiveSheet();
$sql = "INSERT INTO `testCommission` (`One`, `two`, `three`, `four`, `five`, `six`, `seven`) VALUES (?, ?, ?, ?, ?, ?, ?)";
foreach ($worksheet->getRowIterator() as $row) {
// Fetch data
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$data = [];
foreach ($cellIterator as $cell) {
$data[] = $cell->getValue();
}
What can I do to achieve this with the above script?
You need to detect, when it is the first row, a binary variable like this helps
<?php
require '../vendor/autoload.php';
if (pathinfo($_FILES['upexcel']['name'], PATHINFO_EXTENSION) == 'csv') {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
} else {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}
$spreadsheet = $reader->load($_FILES['upexcel']['tmp_name']);
$worksheet = $spreadsheet->getActiveSheet();
$sql = "INSERT INTO `testCommission` (`One`, `two`, `three`, `four`, `five`, `six`, `seven`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$isheader = 0;
foreach ($worksheet->getRowIterator() as $row) {
// Fetch data
if($isheader > 0) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$data = [];
foreach ($cellIterator as $cell) {
$data[] = $cell->getValue();
}
} else
{ $isheader = 1; }
}
?>
Use a filter class.
See docs:
https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-files/#reading-only-specific-columns-and-rows-from-a-file-read-filters
Don't forget the autoload:
require_once ( 'vendor/autoload.php' );
Create a filter:
class FirstRowFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Return true for rows after first row
return $row > 0;
}
}
Apply to the reader:
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$filterRow = new FirstRowFilter();
$reader->setReadFilter($filterRow);
Load file:
$spreadsheet = $reader->load($file);
The reader will only load rows after the specified row.
Related
Is it possible by code to skip the Header (Top Row) in Excel Spreadsheet?
I'm using PHPExcel_Reader to process upload into database.
this image is my data excel
this is my code:
<?php require_once('../../php-excel-reader/excel_reader2.php'); require_once('../../SpreadsheetReader.php'); if (isset($_POST["import"])) { $allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; if(in_array($_FILES["file"]["type"],$allowedFileType)){ $targetPath = '../assets/uploads/'.$_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'], $targetPath); $Reader = new SpreadsheetReader($targetPath); $sheetCount = count($Reader->sheets()); for($i=0;$i<$sheetCount;$i++) { $Reader->ChangeSheet($i); foreach ($Reader as $Row) { $student_id = ""; if(isset($Row[0])) { $student_id = mysqli_real_escape_string($conn,$Row[0]); } $roll_no = ""; if(isset($Row[1])) { $roll_no = mysqli_real_escape_string($conn,$Row[1]); } $student_name = ""; if(isset($Row[2])) { $student_name = mysqli_real_escape_string($conn,$Row[2]); } $class_name = ""; if(isset($Row[3])) { $class_name = mysqli_real_escape_string($conn,$Row[3]); } ?>
I use this method for skip header :
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('FILE.xlsx');
$sheetData = array();
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$sheetData[$row][$col] = $val;
}
}
}
unset($sheetData[1]); // SKIP HEADER
foreach ($sheetData as $val) {
// set data for upload DB
}
i just unset that from array.
I'm still at the first stage of learning. Here is my problem: I want to skip the first row of an Excel file to upload it into the database. I hope you can help me to solve this.
Here is the code:
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$period = "";
if(isset($Row[0])) {
$period = mysqli_real_escape_string($conn,$Row[0]);
}
$target = "";
if(isset($Row[1])) {
$target = mysqli_real_escape_string($conn,$Row[1]);
}
$achieved = "";
if(isset($Row[2])) {
$achieved = mysqli_real_escape_string($conn,$Row[2]);
}
$batch = "";
Use continue to skip processing for just the first row.
foreach ($Reader as $index => $Row) {
if ($index === 0) {
continue;
}
// process $Row
}
This assumes $Reader has a zero-based index.
I am trying to populate a mysql database with an excel file using phpspreadsheet library. I am doing it in the following way but I get just the first row. How can I do it for all the rows
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($target_file);
$worksheet = $spreadsheet->getActiveSheet();
$rows = [];
$outer = 1;
foreach ($worksheet->getRowIterator() AS $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
$cells = [];
foreach ($cellIterator as $cell) {
$cells[] = $cell->getValue();
}
$rows[] = $cells;
while($outer > 1){
$data = [
'testTaker' => $cells[1],
'correctAnswers' => $cells[2],
'incorrectAnswers' => $cells[3],
];
if($this->testModel->addTest($data)){
die('it worked');
} else {
die('Something went wrong');
}
}
$outer++;
}
This is how I am importing a XLSX spreadsheet with phpSpreadSheet into a MySQL database using PDO (modified to fit your criteria).
// read excel spreadsheet
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
if($reader) {
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($target_file);
$sheetData = $spreadsheet->getActiveSheet()->toArray();
foreach($sheetData as $row) {
// get columns
$testTaker = isset($row[0]) ? $row[0] : "";
$correctAnswers = isset($row[1]) ? $row[1] : "";
$incorrectAnswers = isset($row[2]) ? $row[2] : "";
// insert item
$query = "INSERT INTO item(testTaker, correctAnswers, incorrectAnswers) ";
$query .= "values(?, ?, ?)";
$prep = $dbh->prepare($query);
$prep->execute(array($testTaker, $correctAnswers, $incorrectAnswers));
}
}
I want to import data using php mysql from excel sheet containing 1.6 million records. What is the best way to do this?
this is the sample code I have used to iterate excel file and insert data in database:
public function iterateData($file_name) {
$fileDirectory = '';
$file_name = $fileDirectory . $file_name;
if (file_exists($file_name)) {
$this->truncateTable();
include 'PHPExcel2/Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file_name);
$count = 1;
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true); // Loop all cells, even if it is not set
$cellValues = array();
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
$cellValues[] = $cell->getCalculatedValue();
}
}
if (isset($cellValues[0]) && $cellValues[0] != 'Product' && $cellValues[0] != '') {
$this->inserInDatabase($cellValues);
} elseif (empty($cellValues[0]) && empty($cellValues[1]) && empty($cellValues[2])) {
continue;
}
}
if ($objPHPExcel->getSheetCount() == $count) {
return TRUE;
}
$count++;
}
} else {
return FALSE;
}
} private function inserInDatabase($data) {
$dbDetails = array(
'db_name' => '*',
'db_pass' => '*',
'db_host' => 'localhost',
'db_user' => '*'
);
$dbh = dbConnect::connect($dbDetails);
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO product_description (product_id, prpoduct_description, price, created_date) values ('" . mysql_escape_string($data[0]) . "', '" . mysql_escape_string($data[1]) . "', '" . mysql_escape_string($data[2]) . "', '$date')";
if (!$dbh->dbh->query($sql)) {
die('Database Connection Failed.');
}
}
export you excel data to csv format, and then import the csv format to mysql
you can import using ;
if($request->hasFile('excelFile')){
$inputFileType = 'Xlsx';
$inputFileName = $request->file('excelFile')->getRealPath();
/** Create a new Reader of the type defined in $inputFileType **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$reader->setReadDataOnly(true);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($inputFileName);
foreach ($spreadsheet->getActiveSheet()->toArray() as $key => $row) {
$data['question'] = $row[0];
$data['option1'] = $row[1];
$data['option2'] = $row[2];
$data['option3'] = $row[3];
$data['option4'] = $row[4];
$data['correct'] = $row[5];
$data['status'] = 1;
$data['receiver'] = 'all';
$data['createdOn'] = date("Y-m-d H:i:s");
if(!empty($data)) {
DB::table('questions')->insert($data);
}
}
}
This is my code,
Please tell me what am I missing?
// Field names in the first row
$sql1 = "SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='test'
AND `TABLE_NAME`='user_tab'";
$res1 = mysql_query($sql1);
while ($row2 = mysql_fetch_assoc($res1)) {
$fields[] = $row2['COLUMN_NAME'];
}
//Data
$sql = "SELECT * FROM user_tab";
$res = mysql_query($sql);
echo date('H:i:s'), " Load from Excel5 template", EOL;
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load("mytest.xls");
$logo = new PHPExcel_Worksheet_HeaderFooterDrawing();
$logo->setName('Logo');
$logo->setPath('image.jpg'); //Path is OK & tested under PHP
$logo->setHeight(38); //If image is larger/smaller than that, image will be proportionally resized
$objPHPExcel->getActiveSheet()->getHeaderFooter()->addImage($logo, PHPExcel_Worksheet_HeaderFooter::IMAGE_HEADER_LEFT);
echo date('H:i:s'), " Add new data to the template", EOL;
$col = 0;
foreach ($fields as $key => $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $value);
$col++;
}
$row = 2;
while ($row_data = mysql_fetch_assoc($res)) {
$col = 0;
foreach ($row_data as $key => $value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save(str_replace('.php', '.xls', __FILE__));