簡體   English   中英

僅使用 PHP 將 Excel 數據導入 mysql 1 張

[英]Import Excel Data to mysql 1 sheet only using PHP

我正在嘗試將成績單導入 mysql 數據庫,但是 excel 文件有多個工作表我如何制作它,所以只有一個指定的工作表會進入我的數據庫

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

}

據我了解,您希望從特定工作表中獲取數據。

PHPExcel中有這個 function: setActiveSheetIndex (sheet_index)

你可以這樣嘗試:

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

我剛剛刪除了 foreach 並添加了 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);
 }  
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM