phpspreadsheet是目前比较流行的office处理包,api也非常简洁明了,使用也很方便,下面就简单讲讲如何导入。
官方文档:https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-files/
安装:composer require phpoffice/phpspreadsheet
$path= iconv("UTF-8","GBK", $path); //文件名称 是将文件转换编码避免乱码
public function save(Request $request)
{
$d = $request->param();
$file = $d['file'];
$file = str_replace('_',".",$d);
$path = '.'.$file["file"];
$path= iconv("UTF-8","GBK", $path); //文件名称
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$data = $spreadsheet
->getSheet(0) // 指定第一个工作表为当前
->toArray(); // 转为数组
// 启动事务
Db::startTrans();
try {
$num_company = 0;//成功导入公司数量
$num_zhengshu = 0;//成功导入证书数量
foreach ($data as $k=> $item) {
if($k > 1){
//公司存在,则不新增公司
$company["name"] = $item[8];
$company["xinyongdaima"] = $item[9];
$company["faren"] = $item[10];
$company["yingyeqixian"] = $item[11];
$company["dengjijiguan"] = $item[12];
$company["zhucedi"] = $item[13];
$company["jingyingfanwei"] = $item[14];
$company["create_time"] = time();
$company["update_time"] = time();
$res = Db::name('enterprise')->where($company)->find();
if(!$res){
$con_id = Db::name('enterprise')->insertGetId($company);
$num_company++;
}else{
$con_id = $res["id"];
}
//信用信息
$zhengshu["pingjileixing"] = $item[1];
$zhengshu["xinyongdengji"] = $item[2];
$zhengshu["zhengshubianma"] = $item[3];
$zhengshu["pingjishijian"] = $item[4];
$zhengshu["youxiaoqizhi"] = $item[5];
$zhengshu["zhidaodanwei"] = $item[6];
$zhengshu["pingjijigou"] = $item[7];
$zhengshu["enterprise_id"] = $con_id;
$zhengshu["create_time"] = time();
$zhengshu["update_time"] = time();
//如果证书编码重复,导入失败
$repeat = Db::name('enterprise_zhengshu')
->where("zhengshubianma",$zhengshu["zhengshubianma"])
->find();
if($repeat){
Db::rollback();
return json(["code"=>4000,"msg"=>"有重复的证书编码,导入失败"]);
}
$res = Db::name('enterprise_zhengshu')->insertGetId($zhengshu);
$num_zhengshu++;
}
}
return json(["code"=>200,"msg"=>"导导入成功:公司{$num_company}家,证书:{$num_zhengshu}个"]);
} catch (\Exception $e) {
// 回滚事务
Db::rollback();
return json(["code"=>4000,"msg"=>"导入失败,内存不足,请使用google浏览器重试"]);
}
}