支持自动识别表头名称和字段并生成对应的数据
目录结构
1.下载php的Excel扩展
扩展地址:https://github.com/PHPOffice/PHPExcel 将下载的扩展放入到/extend 目录下,并改名文件夹为Excel(如上图所示)
2.创建类库文件(\application\webapi\lib\Excel.php )
<?php
namespace app\Webapi\lib;
class Excel {
function get_obj($file_name) {
$phpexcel_path= '../extend/Excel/PHPExcel.php';
require_once $phpexcel_path;
$objReader = null;
$objPHPExcel = null;
$extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if ($extension == 'xlsx') {
$objReader = new \PHPExcel_Reader_Excel2007();
$objPHPExcel = $objReader->load($file_name);
} else if ($extension == 'xls') {
$objReader = new \PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load($file_name);
} else if ($extension == 'csv') {
$PHPReader = new \PHPExcel_Reader_CSV();
$PHPReader->setInputEncoding('GBK');
$PHPReader->setDelimiter(',');
$objPHPExcel = $PHPReader->load($file_name);
}
return $objPHPExcel;
}
function band_title_field($objPHPExcel, $title_field, $cellKey = null) {
$title_item_field = [];
$cellKey = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM',
'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'
];
foreach ($cellKey as $key => $value) {
$title_item = $objPHPExcel->getActiveSheet()->getCell($value . 1)->getValue();
if ($title_item) {
$title[$title_item] = $value;
} else {
break;
}
}
foreach ($title_field as $key => $value) {
if (isset($title[$key])) {
$title_item_field[$value] = $title[$key];
}
}
return $title_item_field;
}
}
3.控制器代码(\application\webapi\controller\Device.php 接口控制器代码截取 )
public function importExcel(){
$file = request()->file('excel');
$info = $file->validate(['size' => 1048576, 'ext' => 'xls,xlsx'])->move('../public/excel_uploads');
$fileName = '../public/excel_uploads/'.$info->getSaveName();
$excel_extend=new Excel();
$objPHPExcel = $excel_extend->excel_extend_get_obj($fileName);
$title_field = [
'姓名' => 'name',
'手机号码' => 'phone',
'入职日期' => 'start_time',
'年龄' => 'age',
'性别' => 'sex',
'身证号码' => 'id_card_number',
'出生日期' => 'birthday',
];
$title_item_field = $excel_extend->excel_extend_band_title_field($objPHPExcel, $title_field);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($i = 2; $i <= $highestRow; $i++) {
$content[$i] = [];
foreach ($title_item_field as $key => $value) {
$content[$i][$key] = $objPHPExcel->getActiveSheet()->getCell($value . $i)->getValue();
}
$data=$content[$i];
if($data['sex']=="男"){
$data['sex']=1;
}else{
$data['sex']=0;
}
}
}
至此结束,可根据自身需求进行扩展或修改代码
|