PHP Excel匯入資料庫資料
有個這樣的需求,按資料庫格式批量匯入資料存入資料庫
在TP框架有封裝好的類 PHPExcel, 注意這是TP5.1框架的代碼
我自己找了找資源寫出來了,話不多說直接上代碼
ini_set('memory_limit','1024M');
if (!empty($_FILES)) {
$file = request()->file('import');
$info = $file->move(ROOT_PATH .'static'. DS . 'uploads' . DS . 'execl');
if ($info) {
//vendor("PHPExcel.PHPExcel"); // Thinkphp5.1之后不支持 vendor
$Worksheet = new \PHPExcel_Worksheet();
$PHPExcel_Cell = new \PHPExcel_Cell(null,null,$Worksheet);
$objPHPExcel = new PHPExcel(); //excel物件
$file_name = ROOT_PATH .'static/uploads/execl/'.$info->getSaveName();
$extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判斷匯入表格后綴格式
if ($extension == 'xlsx') {
$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel =$objReader->load($file_name, $encode = 'utf-8');
} else if ($extension == 'xls'){
$objReader =\PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel =$objReader->load($file_name, $encode = 'utf-8');
}
$sheet =$objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();//總行數
$highestColumn =$sheet->getHighestColumn(); //總列數
//Db::name('goods')->execute('truncate table s_goods'); //清除表中資料
//i是從低級行開始匯入
for ($i = 2; $i <= $highestRow; $i++) {
//data['id']中id是資料庫得欄位名 A是excel得列
$data[$i]['brand_id'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getFormattedValue(); //商品品牌
$data[$i]['category_id'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getFormattedValue(); //商品分類
$data[$i]['goods_name'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getFormattedValue(); //商品名稱
// 一下依次按照你資料庫里的欄位來撰寫
}
// 啟動事務
Db::startTrans();
// 在這里寫你的入庫邏輯代碼
//下面是我舉得列子
// 商品
foreach($data as $k => $v) {
$goods_data = [
'brand_id' => $v['brand_id'],
'category_id' => $v['category_id'],
'goods_name' => $v['goods_name'],
];
$query = Db::name('Goods')->insertGetId($goods_data); //執行添加
if (isset($query) && $query <= 0) {
// 回滾事務
Db::rollback();
}else{
// 提交事務
Db::commit();
}
}
if($query){
$this->success('匯入成功!');
}
}else{
echo $file->getError();
}
}else{
$this->error("請選擇上傳的檔案");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/26906.html
標籤:其他
下一篇:MySQL中的列轉行
