Home > Software design >  Import Excel Data to mysql 1 sheet only using PHP
Import Excel Data to mysql 1 sheet only using PHP

Time:11-30

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

}

CodePudding user response:

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

CodePudding user response:

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