如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
<code class="language-php">use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
</code>
<code> public function import_demo(){
// 设置PHP默认字符集为UTF-8
ini_set('default_charset', 'UTF-8');
//获取表格的大小,限制上传表格的大小5M
$file_size = $_FILES['file']['size'];
if ($file_size > 5 * 1024 * 1024) {
$this->error('文件大小不能超过5M');
exit();
}
// dd($file_size);
//限制上传表格类型
$fileExtendName = substr(strrchr($_FILES['file']["name"], '.'), 1);
//application/vnd.ms-excel 为xls文件类型
if ($fileExtendName == 'csv') {
$this->error('须为xls或xlsx格式,不能是csv格式!');
exit();
}
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
if ($fileExtendName =='xlsx') {
$objReader = IOFactory::createReader('Xlsx');
$filename = $_FILES['file']['tmp_name'];
}elseif ($fileExtendName =='xls') {
$objReader = IOFactory::createReader('Xls');
$filename = $_FILES['file']['tmp_name'];
}elseif ($fileExtendName=='csv') {
$objReader = IOFactory::createReader('Csv');
$filename = $_FILES['file']['tmp_name'];
}
// dd(1);
$reader = IOFactory::createReaderForFile($filename);
$reader->setReadDataOnly(true); // 只读取数据,忽略样式
$spreadsheet = $reader->load($filename);
$sheet = $spreadsheet->getActiveSheet();
$data = $sheet->toArray(null, true, true, true);
// dd($data);
$num_all= 0;
$num_success= 0;
$save_data = [];
$num_add = 0;
$num_update = 0;
foreach($data as $k=>$vo){
if($k>1){
$num_all++;
$save_data[$k] = [
'cid' => $vo['A'],
'title' => mb_convert_encoding(isset_arr_key($vo, 'B', ''), 'UTF-8', 'auto'),
'dy' => isset_arr_key($vo, 'C', ''),
'xh' => isset_arr_key($vo, 'D', ''),
'summary' => isset_arr_key($vo, 'E', ''),
'pic' => isset_arr_key($vo, 'F', ''),
'album' => isset_arr_key($vo, 'G', ''),
'brand' => isset_arr_key($vo, 'H', ''),
'manufacture' => isset_arr_key($vo, 'I', ''),
'append_spe' => isset_arr_key($vo, 'J', ''),
'append_oe' => isset_arr_key($vo, 'K', ''),
'append_ref' => isset_arr_key($vo, 'L', ''),
'append_ada' => isset_arr_key($vo, 'M', ''),
'append_com' => isset_arr_key($vo, 'N', ''),
'append_mou' => isset_arr_key($vo, 'O', ''),
'append' => isset_arr_key($vo, 'P', ''),
'ctime' => time()
];
// dd($save_data);
//移除首字母C-
$save_data[$k]['cid'] = str_replace('C-','',$save_data[$k]['cid']);
//判断是否存在
$is_exist = db('post')->where([['title','=',$save_data[$k]['title']],['status','<>',9]])->find();
if($is_exist){
$is_update = db('post')->where(['id'=>$is_exist['id']])->update($save_data[$k]);
if($is_update){
$num_update++;
}
}else{
$is_add = db('post')->insert($save_data[$k]);
if($is_add){
$num_add++;
}
}
}
}
return jssuccess('导入成功,新增数量:'.$num_add.',修改数量:'.$num_update);
}
die;
}
</code>