原创

phpspreadsheet做excel导入,乱码等解决方案


phpspreadsheet是目前比较流行的office处理包,api也非常简洁明了,使用也很方便,下面就简单讲讲如何导入。

官方文档:https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-files/
安装:composer require phpoffice/phpspreadsheet

  1. $path= iconv("UTF-8","GBK", $path); //文件名称 是将文件转换编码避免乱码
  2. public function save(Request $request)
  3. {
  4. $d = $request->param();
  5. $file = $d['file'];
  6. $file = str_replace('_',".",$d);
  7. $path = '.'.$file["file"];
  8. $path= iconv("UTF-8","GBK", $path); //文件名称
  9. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
  10. $data = $spreadsheet
  11. ->getSheet(0) // 指定第一个工作表为当前
  12. ->toArray(); // 转为数组
  13. // 启动事务
  14. Db::startTrans();
  15. try {
  16. $num_company = 0;//成功导入公司数量
  17. $num_zhengshu = 0;//成功导入证书数量
  18. foreach ($data as $k=> $item) {
  19. if($k > 1){
  20. //公司存在,则不新增公司
  21. $company["name"] = $item[8];
  22. $company["xinyongdaima"] = $item[9];
  23. $company["faren"] = $item[10];
  24. $company["yingyeqixian"] = $item[11];
  25. $company["dengjijiguan"] = $item[12];
  26. $company["zhucedi"] = $item[13];
  27. $company["jingyingfanwei"] = $item[14];
  28. $company["create_time"] = time();
  29. $company["update_time"] = time();
  30. $res = Db::name('enterprise')->where($company)->find();
  31. if(!$res){
  32. $con_id = Db::name('enterprise')->insertGetId($company);
  33. $num_company++;
  34. }else{
  35. $con_id = $res["id"];
  36. }
  37. //信用信息
  38. $zhengshu["pingjileixing"] = $item[1];
  39. $zhengshu["xinyongdengji"] = $item[2];
  40. $zhengshu["zhengshubianma"] = $item[3];
  41. $zhengshu["pingjishijian"] = $item[4];
  42. $zhengshu["youxiaoqizhi"] = $item[5];
  43. $zhengshu["zhidaodanwei"] = $item[6];
  44. $zhengshu["pingjijigou"] = $item[7];
  45. $zhengshu["enterprise_id"] = $con_id;
  46. $zhengshu["create_time"] = time();
  47. $zhengshu["update_time"] = time();
  48. //如果证书编码重复,导入失败
  49. $repeat = Db::name('enterprise_zhengshu')
  50. ->where("zhengshubianma",$zhengshu["zhengshubianma"])
  51. ->find();
  52. if($repeat){
  53. Db::rollback();
  54. return json(["code"=>4000,"msg"=>"有重复的证书编码,导入失败"]);
  55. }
  56. $res = Db::name('enterprise_zhengshu')->insertGetId($zhengshu);
  57. $num_zhengshu++;
  58. }
  59. }
  60. return json(["code"=>200,"msg"=>"导导入成功:公司{$num_company}家,证书:{$num_zhengshu}个"]);
  61. } catch (\Exception $e) {
  62. // 回滚事务
  63. Db::rollback();
  64. return json(["code"=>4000,"msg"=>"导入失败,内存不足,请使用google浏览器重试"]);
  65. }
  66. }
留言反馈
问题反馈渠道,如有软件无法下载或者其他问题可反馈。【由于某种原因,目前留言不展示】
用户需要登录后才能留言反馈