thinkphp5.1 phpexcel 批量导入导出

1.批量导入

public function importExcel(){$authority = $this->getUserAuthority('order_input', 'batch_import');if ($authority['code'] != 0) {return json($authority);}$file = request()->file('files');if(empty($file)){return printMsg(-1, "请上传文件");}// 移动到框架应用根目录/uploads/ 目录下//$info = $file->validate(['size'=>(100*1024*1024),'ext'=>'xls,xlsx'])->move('static/uploads/');$ext_arr = ['xlsx'];//接收文件$file_type = $file->getInfo()['name'];//获取后缀$ext = explode('.', $file_type);$ext = end($ext);//判断时候是限制的文件格式if (!in_array($ext, $ext_arr)) {return printMsg(-1,'文件格式有误,只支持Excel2007,xlsx后缀的文件');}//实例化类库 // 读取excel文件require_once './../extend/PHPExcel/IOFactory.php';require_once './../extend/PHPExcel/PHPExcel.php';if ($ext == 'xls') {$PHPReader = new \PHPExcel_Reader_Excel5();} elseif ($ext == 'xlsx') {$PHPReader = new \PHPExcel_Reader_Excel2007();}$tmp_name = $file->getInfo()['tmp_name'];$objData = $PHPReader->load($tmp_name, $encode = 'utf-8');$excel_array = $objData->getsheet(0)->toArray();//删除表格第一行unset($excel_array[0]);$insertData = [];$userInfo = $this->getTokenUser();$date = date('Y-m-d H:i:s', $this->request->time());if (count($excel_array) > 500){return printMsg(-1,'批量导入行数不能大于500条');}//todo 线上对应的数据$project_name_id = 13;$source = '腾讯游戏';$project_source_detail_id = 115;$depargroup = 29;$designer_uid = 1114;Db::startTrans();try {foreach ($excel_array as $key => $value) {$line = $key+1;try {$d2 = date("Y-m-d",($value[2] - 25569) * 86400);$d3 = date("Y-m-d",($value[3] - 25569) * 86400);$d5 = date("Ym",($value[5] - 25569) * 86400);}catch (Exception $exception){Db::rollback();return printMsg(-1, "第".$line."行,日期格错误");}$line = $key+1;if (empty($value[0])){Db::rollback();return printMsg(-1, "第".$line."行,单号不能为空");}if (empty($value[1])){Db::rollback();return printMsg(-1, "第".$line."行,需求名称不能为空");}if (!$this->isDate($d2)){Db::rollback();return printMsg(-1, "第".$line."行,需求开始日期格式不正确");}if (!$this->isDate($d3)){Db::rollback();return printMsg(-1, "第".$line."行,需求结束日期格式不正确");}if (!is_numeric($value[4])){Db::rollback();return printMsg(-1, "第".$line."行,价格格式不正确");}if (!$this->isDate2($d5)){Db::rollback();return printMsg(-1, "第".$line."行,需求归属日期格式不正确");}$achievementData = ["type"         => 1, #1:报价"project_name" => $project_name_id,"project_name_id" => $project_name_id,"demand_name"  => $value[1],"demander"     => '腾讯',"start_time"   =>  $d2,"end_time"     =>  $d3,"user_id"      => $userInfo['id'],"create_time"  => $date,"update_time"  => $date,];if (!empty($value[0])) {$achievementData['sn'] = trim($value[0]);}$achiveId = $this->orderAchievement->insertGetId($achievementData);$orderInputData = [];$orderData = ['source'   => $source,'project_source_detail_id'   => $project_source_detail_id,'terminal' => '报价','type'     => '报价','nature'   => '报价','text'     => '报价','nitprice' => $value[4],'workload' => 1,'status'   => 1, #1:报价'create_time' => $date,'update_time' => $date,];$orderId = $this->orderModel->insertGetId($orderData);$orderInputData = ['num'          => 1,'project'      => $project_name_id,'order_time'   => $d5,'personnel'    => $userInfo['id'],'order'        => $orderId,'depargroup'   => $depargroup,'type'         => 1, #1:报价'designer_uid' => $designer_uid,'order_achievement_id' => $achiveId,'create_time' => $date,'update_time' => $date,];$this->orderInputModel->insertGetId($orderInputData);$this->newLog('导入报价类');}Db::commit();} catch (\Exception $e) {// 回滚事务Db::rollback();throw new \Exception('导入失败');return printMsg(self::myx_code + 10, "导入失败:" . $e->getMessage());}return printMsg(0, "导入成功");}private function isDate($str) {$pattern = '/^\d{4}-\d{2}-\d{2}$/'; // 使用正则表达式匹配 YYYY-MM-DD 格式的日期if (preg_match($pattern, $str)) {return true;} else {return false;}}private function isDate2($str) {$pattern = '/^\d{4}\d{2}$/'; // 使用正则表达式匹配 YYYY-MM-DD 格式的日期if (preg_match($pattern, $str)) {return true;} else {return false;}}

excel模版文件
在这里插入图片描述

2.批量导出

public function download(Request $request){/*$authority = $this->getUserAuthority('order_input', 'download');if ($authority['code'] != 0) {return json($authority);}$res = controller('OrderAchievement')->index($request, true);*///return printMsg(0, "成功", $res);$order = OrderModel::where('source', '腾讯游戏')->where('status', '0')->select()->toArray();$title = [];foreach ($order as $k => $v) {if (empty($title[$v['terminal']])) {$title[$v['terminal']] = [$v['nature'] => [$v['type'] => [$v['text']]]];} else {if (empty($title[$v['terminal']][$v['nature']])) {$title[$v['terminal']][$v['nature']] = [$v['type'] => [$v['text']]];} else {if (empty($title[$v['terminal']][$v['nature']][$v['type']])) {$title[$v['terminal']][$v['nature']][$v['type']] = [$v['text']];} else {$title[$v['terminal']][$v['nature']][$v['type']][] = $v['text'];}}}}//return printMsg(0, "成功", $title);//die();$fileName = "需求订单";require_once './../extend/PHPExcel/IOFactory.php';require_once './../extend/PHPExcel/PHPExcel.php';$obj = new \PHPExcel();// 设置当前sheet$obj->setActiveSheetIndex(0);// 设置当前sheet的名称$obj->getActiveSheet()->setTitle('需求订单');// 列标$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'];foreach (['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'] as $k => $v) {foreach (['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'] as $sk => $sv) {$cellKey[] = $v . $sv;}}//处理表头标题//$obj->getActiveSheet()->mergeCells('A1:' . $cellKey[(count($title) - 1) + 4] . '1');//合并单元格(如果要拆分单元格是需要先合并再拆分的,否则程序会报错)$obj->setActiveSheetIndex(0)->setCellValue('A1', '需求订单列表(仅腾讯需求)');$obj->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);$obj->getActiveSheet()->getStyle('A1')->getFont()->setSize(11);$obj->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$obj->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);$leftNumber = 4; //左边位移数量// 填充表头$obj->getActiveSheet()->setCellValue('A2', '来源')->setCellValue('B2', '单号')->setCellValue('C2', '项目名称')->setCellValue('D2', '类型');//合并单元格$obj->getActiveSheet()->mergeCells('A2:A5');$obj->getActiveSheet()->mergeCells('B2:B5');$obj->getActiveSheet()->mergeCells('C2:C5');$obj->getActiveSheet()->mergeCells('D2:D5');//居中$obj->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->getActiveSheet()->getStyle('D2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$obj->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->getActiveSheet()->getStyle('B2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->getActiveSheet()->getStyle('C2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->getActiveSheet()->getStyle('D2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);$i = 0;foreach ($title as $k => $v) {$obj->getActiveSheet()->setCellValue(($cellKey[$i + $leftNumber]) . '2', $k);$obj->getActiveSheet()->getStyle(($cellKey[$i + $leftNumber]) . '2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$i2 = $i;foreach ($title[$k] as $kj => $vj) {$i3 = $i;$obj->getActiveSheet()->setCellValue(($cellKey[$i + $leftNumber]) . '3', $kj);$obj->getActiveSheet()->getStyle(($cellKey[$i + $leftNumber]) . '3')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);foreach ($title[$k][$kj] as $skj => $svj) {$i4 = $i;$obj->getActiveSheet()->setCellValue(($cellKey[$i + $leftNumber]) . '4', $skj);$obj->getActiveSheet()->getStyle(($cellKey[$i + $leftNumber]) . '4')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);foreach ($svj as $ik => $iv) {$obj->getActiveSheet()->setCellValue(($cellKey[$i + $leftNumber]) . '5', $iv);$obj->getActiveSheet()->getStyle(($cellKey[$i + $leftNumber]) . '5')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);$i++;}$obj->getActiveSheet()->mergeCells(($cellKey[$i4 + $leftNumber]) . '4' . ':' . ($cellKey[$i + 3]) . '4');}$obj->getActiveSheet()->mergeCells(($cellKey[$i3 + $leftNumber]) . '3' . ':' . ($cellKey[$i + 3]) . '3');}$obj->getActiveSheet()->mergeCells(($cellKey[$i2 + $leftNumber]) . '2' . ':' . ($cellKey[$i + 3]) . '2');}$obj->getActiveSheet()->mergeCells('A1:' . $cellKey[$i + 4] . '1');/*$obj->getActiveSheet()->mergeCells('A2:A3');$obj->getActiveSheet()->mergeCells('B3:B3');$obj->getActiveSheet()->mergeCells('C3:C3');$obj->getActiveSheet()->mergeCells('D3:D3');$obj->getActiveSheet()->mergeCells('E2:G2');$obj->getActiveSheet()->mergeCells('H2:J2');$obj->getActiveSheet()->setCellValue('E3', '首页')->setCellValue('F3', '内页')->setCellValue('G3', '排版')->setCellValue('H3', '首页')->setCellValue('I3', '内页')->setCellValue('J3', '排版');*/// 导出ob_clean();header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');header('Cache-Control: max-age=1');$objWriter = \IOFactory::createWriter($obj, 'Excel2007');$objWriter->save('php://output');}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/487146.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OpenHarmony 串口服务访问

项目介绍 本文档是在eTS项目hap包中实现串口访问的使用说明,通过JS接口开放给上层应用使用。 一、开发环境准备 安装OpenHarmony SDK 1. 在DevEco Studio菜单栏选择Tools->SDK Manager 2. OpenHarmony SDK选项中选择配备API版本进行安装 二、创建eTS项目 创…

【论文阅读笔记】Revisiting RCAN: Improved Training for Image Super-Resolution

论文地址:https://arxiv.org/abs/2201.11279 代码地址:https://github.com/zudi-lin/rcan-it 论文小结 本文的工作,就是重新审视之前的RCAN,然后做实验来规范化SR任务的训练流程。 此外,作者得出一个结论:…

恒创科技:香港服务器和香港云服务器哪个好啊?

"香港服务器"和"香港云服务器",是两种不同的香港区域的服务器,免备案,都有各自的优势和适用场景,取决于您的需求和预算。以下是它们的一些区别和特点: 香港服务器: 物理服务器&#xf…

【算法与数据结构】回溯算法、贪心算法、动态规划、图论(笔记三)

文章目录 七、回溯算法八、贪心算法九、动态规划9.1 背包问题9.2 01背包9.3 完全背包9.4 多重背包 十、图论10.1 深度优先搜索10.2 广度优先搜索10.3 并查集 最近博主学习了算法与数据结构的一些视频,在这个文章做一些笔记和心得,本篇文章就写了一些基础…

微服务学习

一、服务注册发现 服务注册就是维护一个登记簿,它管理系统内所有的服务地址。当新的服务启动后,它会向登记簿交待自己的地址信息。服务的依赖方直接向登记簿要Service Provider地址就行了。当下用于服务注册的工具非常多ZooKeeper,Consul&am…

【打包 Qt软件给客户使用操作】

文章目录 前言一、使用步骤1.调整为release 版本2.运行,在release 中找到执行文件3. 拷贝.exe文件到某个新建文件夹的目录4.找到自带编译器版本5.点击进入目录6. 执行 执行 windeployqt xxx.exe7.打包完成8.绿色版9.保存打包记录 总结 前言 提示:这里可…

转运机器人,AGV底盘小车:打造高效、精准的汽车电子生产线

为了满足日益增长的市场需求,保持行业领先地位,某汽车行业电子产品企业引入富唯智能AMR智能搬运机器人及其智能物流解决方案,采用自动化运输措施优化生产节拍和搬运效率,企业生产效率得到显著提升。 项目背景: 1、工厂…

【软件测试】定位前后端bug总结+Web/APP测试分析

目录:导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结(尾部小惊喜) 前言 1、Web测试中简单…

Promethues的Agent 模式代理转发的实施教程

目录 一、为什么需要代理转发? 二、Prometheus Agent模式的实施步骤 1、升级Prometheus的版本 2、配置B服务器的配置文件 3、启动代理点B服务器的Prometheus 4、接收端C服务器的Prometheus的安装同步骤1 5、启动接收端C服务器的Prometheus 6、验证是否能够正…

.net core wbeapi 关于swagger的配置

当创建好一个webapi之后,在Program.cs中注释掉原本的AddSwaggerGen,修改为如下配置 Program.cs //builder.Services.AddSwaggerGen();builder.Services.AddSwaggerGen(options >{options.SwaggerDoc("v1", new OpenApiInfo{Version "…

使用Makefile对多个shell命令进行编排

一、背景 在日常运维过程中,我们都会需要写大量的shell命令,如果是工程相对复杂的话,shell命令往往会封装为函数,交由主函数按需调用。 本文将引入Makefile来对复杂shell命令进行封装,让其变得易读易懂。 下面以一个…

【Linux】 login命令使用

login命令 在 Linux 中用于创建一个新的会话,并在新会话中登录用户。这个命令通常在终端中自动执行,当你打开一个新的终端会话或者通过 SSH 远程连接到 Linux 服务器时。 在命令后面附加欲登入的用户名称,它会直接询问密码,等待…