Excel 導(dǎo)入學(xué)生信息
1.前言
有些時候?qū)W生信息是按照統(tǒng)一格式記錄在 Excel
上的,若有 Excel
導(dǎo)入功能直接將這些信息導(dǎo)入到數(shù)據(jù)庫,就會方便很多,本小節(jié)主要介紹一下如何在 ThinkPHP
中使用 phpspreadsheet
三方工具來導(dǎo)入學(xué)生信息。
2.phpspreadsheet 簡介
phpspreadsheet
是一個用純 PHP
編寫的庫,提供了一組類可以讀取和寫入不同的電子表格文件格式,phpspreadsheet
提供了豐富的API接口,可以設(shè)置諸多單元格以及文檔屬性,包括樣式、圖片、日期、函數(shù)等等諸多應(yīng)用,phpspreadsheet
能用程序?qū)崿F(xiàn)各種各樣的樣式的 Excel
表格。
3.安裝 phpspreadsheet
使用如下 composer
命令即可開始安裝 phpspreadsheet
:
composer require phpoffice/phpspreadsheet
如下圖所示:
安裝完如下圖所示:
4.Excel 文件處理
4.1 創(chuàng)建 excel 測試數(shù)據(jù)文件
為了方便演示,需要先手動創(chuàng)建 excel
文件,文件內(nèi)容如下圖所示:
4.2 創(chuàng)建 Excel 文件上傳路由
按照之前第 22
小節(jié)文件上傳的方式新建路由如下:
//文件上傳界面
Route::get('file','file/index');
//文件上傳
Route::post('upload','file/upload');
4.3 創(chuàng)建 Excel 文件上傳處理方法
制器和文件上傳界面方法如下:
public function uploadExcel()
{
$data = $this->request->param();
$file_url = "./upload/" . $data['file_url'];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_url);
$n = 2;
while (true) {
$name = $spreadsheet->getActiveSheet()->getCell('A' . $n)->getValue();
$age = $spreadsheet->getActiveSheet()->getCell('B' . $n)->getValue();
$id_number = $spreadsheet->getActiveSheet()->getCell('C' . $n)->getValue();
try {
$studentModel = new StudentModel();
$studentModel->name = $name;
$studentModel->age = $age;
$studentModel->id_number = $id_number;
$studentModel->created_at = time();
$studentModel->save();
} catch (\Exception $exception) {
}
if(empty($name) && empty($age) && empty($id_number)){
break;
}
$n++;
}
return $this->success('導(dǎo)入成功');
}
5.視頻演示
6.小結(jié)
本小節(jié)介紹了如何使用 phpspreadsheet
導(dǎo)入 excel
中的數(shù)據(jù),然后讀取數(shù)據(jù)到 php
中,再將這些數(shù)據(jù)插入到數(shù)據(jù)庫,需要注意的是在填寫 Excel
數(shù)據(jù)的時候需要按照統(tǒng)一的格式,數(shù)據(jù)入庫的時候需要處理數(shù)據(jù)異常的情況,若出現(xiàn)數(shù)據(jù)異常則可以直接跳過該行繼續(xù)執(zhí)行下一行,直到處理行所有數(shù)據(jù)為空就停止處理,最終達(dá)到導(dǎo)入數(shù)據(jù)的目的。