ThinkPHP6 的Excel匯入與匯出
阿新 • • 發佈:2021-01-08
Excel匯入匯出功能我們經常用到,下面記錄自己的實現方法。Helper類PHPExcelHelper 可以直接拿過來使用。在控制器中實現資料組裝,model中實現資料驗證,最後匯入或匯出。
helper類中匯出匯入的寫法
namespace app\common\helper;
use app\common\constant\SystemConstant;
use PHPExcel;
trait PHPExcelHelper
{
/**
* excel表格匯出
* @param string $fileName 檔名稱
* @param array $headArr 表頭名稱
* @param array $data 要匯出的資料
* @author static7
*/
private function excelExport($fileName = '', $headArr = [], $data = [])
{
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties();
$keyA = ord("A"); // 設定表頭
foreach ($headArr as $v) {
$colum = chr($keyA);
$objPHPExcel-> setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
$keyA += 1;
}
$column = 2;
$objActSheet = $objPHPExcel->getActiveSheet();
foreach ($data as $key => $rows ) { // 行寫入
$span = ord("A");
foreach ($rows as $keyName => $value) { // 列寫入
//判斷資料是否有陣列,如果有陣列,轉換成字串
if(is_array($value)){
$value = implode("、", $value);
}
$objActSheet->setCellValue(chr($span) . $column, $value);
$span++;
}
$column++;
}
$fileName .= "_" . date("Y_m_d", time()) . ".xls";
//$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
//$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名錶
$objPHPExcel->setActiveSheetIndex(0); // 設定活動單指數到第一個表,所以Excel開啟這是第一個表
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=" . $fileName);
header('Cache-Control: max-age=0');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output'); // 檔案通過瀏覽器下載
exit();
}
//匯入函式
private function excelImport($file)
{
header("content-type:text/html;charset=utf-8");
//檔案上傳到伺服器,返回檔案的路徑
$info = $this->uploadFile($file);
//$objPHPExcel = new PHPExcel();
//獲取檔案字尾
$suffix = $this->getExtension($info);
//判斷哪種型別
if ($suffix == "xlsx") {
$reader = \PHPExcel_IOFactory::createReader('Excel2007');
} else {
$reader = \PHPExcel_IOFactory::createReader('Excel5');
}
//載入excel檔案
$file_path = public_path().'public\storage\\'.$info;
//$file_path = root_path() . "public\storage". $info;
$excel = $reader->load($file_path);
//讀取第一張表
$sheet = $excel->getSheet(0);
//獲取總行數
$row_num = $sheet->getHighestRow(); //var_dump($row_num);die;
//獲取總列數
$col_num = $sheet->getHighestColumn();
if($sheet){
return $sheet;
}else{
return false;
}
}
}
在控制器中
匯出
public function export(Request $request)
{
$ids = $request->post('ids');
$user = UserModel::field('id,user_name,account,sex,phone,email,pid as post,oid as organization,star,is_post');
//如果有選擇時,匯出部分
if (!empty($ids)) {
$user = $user->whereIn('id',$ids)->select()->toArray();
}else{
//匯出全部
$user = $user->select()->toArray();
}
$headArr = ['ID', '姓名', '帳號', '性別', '手機號', '郵件', '崗位', '部門', '星級', '是否在職'];
$fileName = '成員表資訊表';
if (empty($user)) {
ajaxR(SystemConstant::SYSTEM_FAILURE, 'no data');
}
$res = $this->excelExport($fileName, $headArr, $user);
if ($res) {
ajaxR(SystemConstant::SYSTEM_SUCCESS, 'ok', $res);
} else {
ajaxR(SystemConstant::SYSTEM_FAILURE, '匯出失敗');
}
}
匯入寫法
//excel匯入 excelImport 需要上傳檔案,傳遞匯入檔案的頭資訊,需要解析出檔案的內容,表頭
public function import(Request $request)
{
$file = $request->file('user_file');
if (empty($file)) {
ajaxR(SystemConstant::SYSTEM_FAILURE, 'File empty!:(');
}
//寫法一
//------------------------------------------------------------
//檔案上傳,並讀取檔案中的資料
$sheet = $this->excelImport($file)->toArray();
if(!$sheet){
ajaxR(SystemConstant::SYSTEM_FAILURE,'Data empty!:(');
}
//讀取第一張表
//獲取總行數
array_shift($sheet); //刪除第一個陣列(標題);
//組裝資料,以及校驗轉化
$data = [];
$i = 0;
foreach ($sheet as $k => $v) {
if(empty(array_filter($v))){
continue;
}
if(is_numeric($v[1])){ //如果是數字強制轉換
$v[1] = (int)$v[1];
}
$data[$k]['user_name'] = $v[1];
$data[$k]['pwd'] = md5('123456');
//判斷是否有重複的賬號
$account = $this->get_user_fields(['account'=>$v[2]],'account');
if($account){
ajaxR(SystemConstant::SYSTEM_FAILURE,'The account '.$v[2].' is exist!:)');
}
$data[$k]['account'] = $v[2];
//判斷性別
if($v[3] == '男'){
$data[$k]['sex'] = 1;
}elseif ($v[3]=='女'){
$data[$k]['sex'] = 2;
}else{
$data[$k]['sex'] = 0;
}
$data[$k]['phone'] = $v[4];
$data[$k]['email'] = $v[5];
//根據excel中崗位判斷崗位id
$pid = $this->get_post_id($v[6]);
$data[$k]['pid'] = $pid;
//判斷部門
if($v[7]){
$oid = $this->get_organization_id(['Organization_Name'=>$v[7]],'id')->id;
}else{
$oid = null;
}
$data[$k]['oid'] = $oid;
if($v[8]){
$star = $v[8];
}else{
$star = 0;
}
$data[$k]['star'] = $star;
//判斷是否在職
if($v[9] == '離職'){
$is_post = 1;
}else{
$is_post = 0;
}
$data[$k]['is_post'] = $is_post;
$i++;
}
//-----------------------------------------
//寫法2
//--------------------------------------------------------------------------
//檔案上傳,並讀取檔案中的資料
/*$sheet = $this->excelImport($file);
$row_num = $sheet->getHighestRow();
if(!$sheet){
ajaxR(SystemConstant::SYSTEM_FAILURE,'Data empty!:(');
}
$data = []; //陣列形式獲取表格資料
for ($i = 2; $i <= $row_num; $i++) {
$data[$i]['user_name'] = $sheet->getCell("B" . $i)->getValue();
$data[$i]['pwd'] = md5(123456);
//判斷是否有重複的賬號
$account = $sheet->getCell("C" . $i)->getValue();
$accounts = $this->get_user_fields(['account'=>$account],'account');
if($accounts){
ajaxR(SystemConstant::SYSTEM_FAILURE,'The account '.$accounts.' is exist!:)');
}
$data[$i]['account'] = $account;
//判斷性別
$sex = $sheet->getCell("D" . $i)->getValue();
if($sex == "男"){
$sex = 1;
}elseif ($sex ==2){
$sex =2;
}else{
$sex = 0;
}
$data[$i]['sex'] = $sex;
$data[$i]['phone'] = $sheet->getCell("E" . $i)->getValue();
$data[$i]['email'] = $sheet->getCell("F" . $i)->getValue();
//判斷崗位id
$p_name = $sheet->getCell("G" . $i)->getValue();
$pid = $this->get_post_id($p_name);
$data[$i]['pid'] = $pid;
//判斷組織機構id
$o_name = $sheet->getCell("H" . $i)->getValue();
if($o_name){
$oid = $this->get_organization_id(['Organization_Name'=>$o_name],'id')->id;
}else{
$oid = null;
}
$data[$i]['oid'] = $oid;
$data[$i]['star'] = $sheet->getCell("I" . $i)->getValue();
//判斷是否在職
$is_post = $sheet->getCell("J" . $i)->getValue();
if($is_post == '離職'){
$is_post = 1;
}else{
$is_post = 0;
}
$data[$i]['is_post'] = $is_post;
}
if (empty($data)) {
ajaxR(SystemConstant::SYSTEM_FAILURE,'資料解析失敗');
}
//判斷需要匯入的資料中,是否有重複的account
$account_array = array_column($data,'account'); //輸出陣列中account的值
$accounts = implode(',',$account_array);
//$account_result = Db::name('user')->field('account')->where('account','in',$account_array)->select()->toArray();
$account_result = UserModel::field('account')->whereIn('account',$account_array)->select();
if(count($account_result)){
ajaxR(SystemConstant::SYSTEM_FAILURE,'The account '.$accounts.' is exist!:)');
}*/
//--------------------------------------------------------------------------------
if($data){
//儲存$data
/* $user = new UserModel();
$user = $user->saveAll($data);*/
$user_num = Db::name('user')
->limit(100)
->insertAll($data); //返回插入的條數
$result = [
'user_num'=>$user_num
];
if($result){
ajaxR(SystemConstant::SYSTEM_SUCCESS,'success!:)',$result);
}else{
ajaxR(SystemConstant::SYSTEM_FAILURE,'save fail!:(');
}
}else{
ajaxR(SystemConstant::SYSTEM_FAILURE,'Data is wrong,It is fail! :(');
}
}