How to Skip Header from Excel Spreadsheet While Uploading to MySQL - php

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.

Related

How to prevent duplicate data when importing excel using PHPexcel in Codeigniter

public function import_excel(){
if (!$_FILES["file"]["name"]) {
echo "Please upload excel file !";
} else {
$path = $_FILES["file"]["tmp_name"];
$object = PHPExcel_IOFactory::load($path);
foreach ($object->getWorksheetIterator() as $worksheet) {
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++) {
$group = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
$merchant_id = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$login_id = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
$play_id = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
$mem_name = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
$data[] = array(
'group' => $group,
'merchant_id' => $merchant_id,
'login_id' => $login_id,
'play_id' => $play_id,
'mem_name' => $mem_name,
);
}
}
$this->db->insert_batch('excel_files', $data);
}
}
This code is working when upload excel, but I wonder when user upload excel 50 rows, the day after upload again 65 rows, the 65 rows no need to duplicate.
you can do some check, in your looping code
public function import_excel(){
if (!$_FILES["file"]["name"]) {
echo "Please upload excel file !";
} else {
$path = $_FILES["file"]["tmp_name"];
$object = PHPExcel_IOFactory::load($path);
foreach ($object->getWorksheetIterator() as $worksheet) {
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++) {
$group = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
$merchant_id = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$login_id = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
$play_id = $worksheet->getCellByColumnAndRow(3, $row)->getValue();
$mem_name = $worksheet->getCellByColumnAndRow(4, $row)->getValue();
$data[] = array(
'group' => $group,
'merchant_id' => $merchant_id,
'login_id' => $login_id,
'play_id' => $play_id,
'mem_name' => $mem_name,
);
}
}
//-- check duplicate here
$dataCheck = $this->methodCheck($data);
if($dataCheck==true)
{
$this->db->insert_batch('excel_files', $data);
}
}
}
function methodCheck($param){
$this->db->select("*");
$this->db->from("yourInsertedTable");
foreach($param as $searchKey=>$searchValue){
$this->db->where($searchKey,$searchValue);
}
$hasil=$this->db->get('')->result_array();
if(isset($hasil))
{
return false;
}else{
return true;
}
}

How do I skip first row of Excel in order to upload into my database

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.

PHPExcell get cell value and cell color?

How to get cell values and cell colors from spreadsheet-reader-master or PHPExcell?
<?php
require('spreadsheet-reader-master/php-excel-reader/excel_reader2.php'); //spreadsheet-reader-master
require('spreadsheet-reader-master/SpreadsheetReader.php'); //spreadsheet-reader-master
$reader = new SpreadsheetReader('Book1.xlsx'); // xlsx file
foreach ($reader as $key ) {
//foreach loop
echo "<pre>";
print_r($key);
}
<?php
require('./PHPExcel-1.8/Classes/PHPExcel.php');
$tmpframe = './Book1.xlsx';
$exceReader = PHPExcel_IOFactory::createReaderForFile($tmpframe);
$excelObj = $exceReader->load($tmpframe);
$worksheet = $excelObj->getActiveSheet();
$lastRow = $worksheet->getHighestRow();
// $highestRow = $sheet->getHighestRow();
// $highestColumn = $worksheet->getHighestColumn();
$rowl = $worksheet->getHighestRow();
$coll = $worksheet->getHighestColumn();
echo "number of rows---".$rowl."<br>";
echo "number of column---".$coll."<br>";
$rowdumy = 20;
$crt = 'QT';
$crt++;
for ($row=1; $row <= $rowdumy; $row++) {
echo "<h6>number of-----".$row."</h5><br>";
for ($i = 'A'; $i !== $crt; $i++){
$cell = $worksheet->getCell($i.$row);
$colurc = $excelObj->getActiveSheet()->getStyle($i.$row)->getFill()->getStartColor()->getARGB();
if($cell != '')
{
echo $cell."-[[".$colurc."]]";
}
}
echo "<br>";
}
?>

Using array_map when importing data from xlsx

I am importing some data into a mysql table from an xls file.
On the data, i want to use the mysqli_real_escape_string function, before i insert it into the sql table.
My question is that: where should i put the array_map with the escape function in this code below?
Thanks for help.
if(isset($_POST['submitButton']))
{
if($_FILES['file']['size'] != 0 )
{
if($_FILES["file"]["size"] > 5242880 ) { $error[] = "A fájl mérete maximum 5 MB lehet."; }
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $fajl_types)) { $error[] = "Nem engedélyezett fájl típus."; }
if(count($error) == 0 )
{
$path = "../imports/" . date( "Y-m-d" ) . '-' . rand(1, 9999) . '-' . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'], $path ))
{
$file_name = basename($path);
$objPHPExcel = PHPExcel_IOFactory::load('../imports/'.$file_name);
$dataArr = array();
foreach($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$dataArr[$row][$col] = $val;
}
}
}
unset($dataArr[1]); // since in our example the first row is the header and not the actual data
$user_pass = "";
$user_reg_date = date("Y-m-d-H:i:s");
$user_last_login = "";
$user_aktivation = "";
$user_vevocsoport = (int)0;
$user_newpass = "";
$user_imported = (int)1;
foreach($dataArr as $val)
{
$sql = "INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
'".$val['0']."',
'".$val['1']."'
)";
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}
}
else
{
$error[] = "A fájl feltöltése nem sikerült.";
}
}
}
else
{
$error[] = "Nem választott ki fájlt.";
}
}
You can add it when building the query. Like this, the escaping and building the query, which are both related to each other, are close to each other in your code.
foreach($dataArr as $val)
{
$escapedVals = array_map(function($value) use ($kapcs) {
return mysqli_real_escape_string($kapcs, $value);
}, array_slice($val, 0, 2));
$sql = 'INSERT INTO user
(
user_vnev,
user_knev
)
VALUES
(
"' . implode ('","', $escapedVals) . '"
)';
$import = mysqli_query($kapcs, $sql) or die("IMPORT-ERROR - " . mysqli_error($kapcs));
$ok = 1;
}

How to get row id using color code in phpexcel

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

Categories