php TP6 用Excel導入數據至數據庫


//phpexcel類庫github下載地址為https://github.com/PHPOffice/PHPExcel 
//把里面的Classes文件夾解壓放到vendor文件夾下的phpexcel文件夾下沒有則創建

public function excel_import()
{
ini_set('memory_limit', '1024M');
if ($this->request->isPost()) {
$file = request()->file('file');
      //引入第3方類庫 (引入方式有多種,如果這種不行 可以試試其他)注意文件名別搞錯了
require "../vendor/phpexcel/PHPExcel.php";
require "../vendor/phpexcel/PHPExcel/IOFactory.php";


header("Content-type:text/html;charset=utf-8");
//實例化主文件
//接收前台傳過來的execl文件
$file = $_FILES['file'];
//截取文件的后綴名,轉化成小寫
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($extension == "xlsx") {
//2007(相當於是打開接收的這個excel)
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
} else {
//2003(相當於是打開接收的這個excel)
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
}

$objContent = $objReader->load($file['tmp_name']);

if ($objContent) {
$sheetContent = $objContent->getSheet(0)->toArray();
//刪除第一行標題

unset($sheetContent[0]);
//dump($sheetContent);die();
        //切記excel表格順序下標跟對應字段不要弄錯
foreach ($sheetContent as $k => $v) {
$arr['certificate_number'] = $v[0];
$arr['real_name'] = $v[1];
$arr['sfz'] = $v[2];
$arr['create_time'] = time();
$arr['sc_id'] = $school_info['sc_id'];
$arr['type'] = $school_info['type'];
$res[] = $arr;
}

        //執行寫入
$re = Db::table('certificate')
->insertAll($res);
if ($re) {
$this->success('導入成功 !');
} else {
$this->error('導入失敗 !');
}
} else {
$this->error('請導入表格 !');
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM