ThinkPHP6 自定义Excel导出

一、说明

1.需要安装Spreadsheet,如未安装自行composer安装即可

2.定义导出表格的表头(及键值)

3.数据内容需要与定义的表头一致

二、核心代码

try {//  获取表格数据$list = (new Activity())->select()->toArray();if (!empty($list)) {// 设置key$key = [['key' => 'index', 'title' => '序号'],['key' => 'activity_name', 'title' => '名称'],['key' => 'student_name', 'title' => '学生姓名'],];$sheet = new Spreadsheet();$activeSheet = new ExcelLogic($sheet);//  计算总列数$allColumn = count($key);//  计算总行数$allRow = count($list);//  重制表格数据,与键值对应$newArr = [];foreach ($list as $k => $v) {$newArr[$k]['index'] = $k + 1;$newArr[$k]['activity_name'] = $v['activity']['title'];$newArr[$k]['student_name'] = $v['student']['name'];}//  添加表内容for ($i = 0; $i < $allColumn; $i++) {//  设置标题$activeSheet->setCellsValue(1, $i + 1, $key[$i]['title'])->setAlign(1, $i + 1)->setrgBgColor(1, $i + 1, 1, '7f89e6')->setFont(1, $i + 1, 1, 'ffffff')->setBorder(1, $i + 1)->setRowAndCol(1, $i + 1, 24, strlen($key[$i]['title']));//  设置内容for ($j = 0; $j < $allRow; $j++) {$rowData = $newArr[$j][$key[$i]['key']];$activeSheet->setCellsValue($j + 2, $i + 1, strval($rowData))->setAlign($j + 2, $i + 1)->setBorder($j + 2, $i + 1);}}//  导出表格$writer = IOFactory::createWriter($sheet, 'Xlsx');//创建excel文件$exportCache = new ExportCache();$src = $exportCache->getSrc();if (!file_exists($src)) {mkdir($src, 0775, true);}$filename = '报名列表数据导出_' . date('YmdH') . '.xlsx';$writer->save($src . $filename);//    返回下载地址}return $this->success('', ['url' => ''], 2);} catch (\Exception $e) {return $this->fail($e->getMessage());}

三、ExcelLogic类

<?phpnamespace app\common\logic;use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;/*** @note Excel处理*/
class ExcelLogic
{//  定义sheetprivate object $sheet;//  定义当前操作工作表private object $currentSheet;/*** @note 初始化* @param object $sheet* @param int $sheetIndex*/public function __construct(object $sheet, int $sheetIndex = 0){$this->sheet = $sheet;
//        $this->sheet = new Spreadsheet();$this->currentSheet = $this->sheet->getActiveSheet($sheetIndex);}/*** @notes 设置工作表名* @param string $title 表名* @return ExcelLogic*/public function setTitle(string $title = '模板'): ExcelLogic{$this->currentSheet->setTitle($title);return $this;}/*** @notes 设置字体样式* @param int $row 行* @param int $col 列* @param string $fontName 字体名称* @param string $fontSize 字体大小* @param bool $isBold 是否加粗* @param string $fontColor 字体颜色* @param bool $isWrap 是否自动换行* @param int $colSpan 列跨度* @return ExcelLogic*/public function setFont(int    $row = 1,int    $col = 1,int    $colSpan = 1,string $fontColor = '000000',bool   $isBold = false,string $fontName = '宋体',string $fontSize = '14',bool   $isWrap = true,): ExcelLogic{$this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getFont()->setName($fontName)->setSize($fontSize)->setBold($isBold)->setColor(new Color($fontColor));// 自动换行$this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getAlignment()->setWrapText($isWrap);return $this;}/*** @notes 设置文字对齐方式* @param int $row 行* @param int $col 列* @param string $alignHorizontal 水平对齐方式* @param string $alignVertical 垂直对齐方式* @return ExcelLogic*/public function setAlign(int $row = 1, int $col = 1, string $alignHorizontal = 'center', string $alignVertical = 'center'): ExcelLogic{//  水平居中$this->currentSheet->getStyleByColumnAndRow($col, $row)->getAlignment()->setHorizontal($alignHorizontal);//  垂直居中$this->currentSheet->getStyleByColumnAndRow($col, $row)->getAlignment()->setVertical($alignVertical);return $this;}/*** @notes 行高及列宽* @param int $row 行* @param int $col 列* @param int $rowHeight 行高* @param int $colWidth 列宽* @return ExcelLogic*/public function setRowAndCol(int $row = 1, int $col = 1, int $rowHeight = 24, int $colWidth = 20): ExcelLogic{//  设置行高$this->currentSheet->getRowDimension($row)->setRowHeight($rowHeight);$this->currentSheet->getColumnDimensionByColumn($col)->setWidth($colWidth);return $this;}/*** @notes 设置边框* @param int $row 开始行* @param int $col 开始列* @param int $colSpan 列合并数* @param string $borderStyle 边框样式* @param string $borderColor 边框颜色* @return ExcelLogic*/public function setBorder(int    $row = 1,int    $col = 1,int    $colSpan = 1,string $borderStyle = 'thin',string $borderColor = '000000'): ExcelLogic{//  设置边框样式$this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getBorders()->getallBorders()->setBorderStyle($borderStyle)->setColor(new Color($borderColor));return $this;}/*** @notes 设置背景色* @param int $row 开始行* @param int $col 开始列* @param int $colSpan 列合并数* @param string $bgColor 背景色* @return ExcelLogic*/public function setrgBgColor(int $row = 1, int $col = 1, int $colSpan = 1, string $bgColor = 'ffffff'): ExcelLogic{//  设置背景色$this->currentSheet->getStyleByColumnAndRow($col, $row, $col + $colSpan - 1, $row)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB($bgColor);return $this;}/*** @notes 设置单元格内容* @param int $row 行* @param int $col 列* @param string $title 表头名称* @param int $dataRow 内容* @param string|int $data 内容* @return ExcelLogic*/public function setCellValue(int        $row = 1,int        $col = 1,string     $title = '序号',string|int $data = '',int        $dataRow = 0,): ExcelLogic{//  设置表头$this->currentSheet->setCellValueByColumnAndRow($col, $row, $title);//  设置内容if ($dataRow == 0) $dataRow = $row + 1;$this->currentSheet->setCellValueByColumnAndRow($col, $dataRow, $data);return $this;}/*** @notes 设置单元格内容* @param int $row 行* @param int $col 列* @param string $data 内容* @return ExcelLogic*/public function setCellsValue(int    $row = 1,int    $col = 1,string $data = '',): ExcelLogic{//  设置内容$this->currentSheet->setCellValueByColumnAndRow($col, $row, $data);return $this;}/*** @notes 合并列并设置内容* @param string $val 单元格内容* @param int $col 开始列* @param int $colSpan 列合并数* @param int $row 合并行* @param string $bgColor 背景色* @param string $align 文字对齐* @param string $fontColor 字体颜色* @param string $fontSize 字体大小* @param bool $isBold 字体粗细* @param string $fontName 字体名称* @param bool $isWrap 是否自动换行* @param float $rowHeight 行高* @return ExcelLogic*/publicfunction mergeCell(string $val,int    $col = 1,int    $colSpan = 1,int    $row = 1,string $bgColor = 'FFFFFF',string $align = 'left',string $fontColor = 'ff4040',string $fontSize = '14',bool   $isBold = true,string $fontName = '宋体',bool   $isWrap = true,float  $rowHeight = 60): ExcelLogic{$this->currentSheet->mergeCellsByColumnAndRow($col, $row, $col + $colSpan - 1, $row);$this->currentSheet->setCellValueByColumnAndRow($col, $row, $val);$this->setFont($row, $col, $colSpan, $fontColor, $isBold, $fontName, $fontSize, $isWrap);$this->setAlign($row, $col, $align);$this->setRowAndCol($row, $col, $rowHeight);$this->setBorder($row, $col, $colSpan);$this->setrgBgColor($row, $col, $colSpan, $bgColor);return $this;}/*** @notes 新建工作表* @param string $title 工作表名称* @param int $sheetIndex 工作表序号* @param array $tableArr 表头数组* @param array $keys 键值数组* @param array $dataArr 数据数组* @return ExcelLogic*/public function createSheet(string $title = 'sheet1', int $sheetIndex = 1, array $tableArr = [], array $keys = [], array $dataArr = []): ExcelLogic{//  新建工作表$newSheet = new Worksheet($this->sheet, $title);$this->sheet->addSheet($newSheet, $sheetIndex);//  计算总列数$totalCol = count($tableArr);$colArr = $this->getColumn($totalCol);//  添加数据内容for ($i = 0; $i < $totalCol; $i++) {//  设置表头$newSheet->setCellValue($colArr[$i] . 1, $tableArr[$i]);for ($j = 0; $j < count($dataArr); $j++) {//  设置内容$newSheet->setCellValue($colArr[$i] . $j + 2, $dataArr[$j][$keys[$i]]);}}return $this;}/*** @notes 自动计算列数* @param string $col*/publicfunction getColumn(int $colNumber = 1){//  生成A-Z的数组$arr = range('A', 'Z');//  计算循环次数$no = ceil($colNumber / count($arr));//  定义数组$data = [];if ($no <= 1) {for ($i = 0; $i < $colNumber; $i++) {$data[] = $arr[$i];}} else {for ($i = 0; $i < count($arr); $i++) {$data[] = $arr[$i];}for ($i = 0; $i < $colNumber - count($arr); $i++) {$list = (($i + count($arr)) % count($arr));$data[] = $arr[ceil(($i + 1) / count($arr)) - 1] . $arr[$list];}}return $data;}
}

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

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

相关文章

机器人跟踪性能量化指标

衡量机械臂关节轨迹跟踪控制的性能可以通过以下几个方面来进行&#xff1a; 跟踪精度&#xff1a;这是衡量机械臂关节轨迹跟踪控制性能的最重要的指标。它反映了机械臂实际运动轨迹与期望运动轨迹之间的偏差。跟踪精度越高&#xff0c;说明机械臂的控制性能越好。运动范围&…

抖音小店怎么选品?分享如何培养选爆品的思维,每个人都要学会

选品定店铺生死。 一个店铺能不能出单&#xff0c;能不能赚钱&#xff0c;店铺的商品占主要部分&#xff0c;商品才是电商店铺最核心的内容&#xff0c;一个货真价实&#xff0c;物美价廉的产品才是店铺的核心竞争力&#xff0c;运营和找达人都是让产品卖的更多&#xff0c;更…

三、MySQL实例初始化、设置、服务启动关闭、环境变量配置、客户端登入(一篇足以从白走到黑)

目录 1、选择安装的电脑类型、设置端口号 2、选择mysql账号密码加密规则 3、设置root账户密码 4、设置mysql服务名和服务启动策略 5、执行设置&#xff08;初始化mysql实例&#xff09; 6、完成设置 7、MySQL数据库服务的启动和停止 方式一&#xff1a;图形化方式 方式…

AI智能剪辑,快速剪辑出需要的视频

AI智能剪辑技术&#xff0c;是一种基于人工智能的技术&#xff0c;它能够通过机器学习和深度学习算法&#xff0c;自动识别视频中的内容&#xff0c;并根据用户的需求和喜好&#xff0c;快速地剪辑出需要的视频。 所需工具 &#xff1a; 一个【媒体梦工厂】软件 视频素材 …

软件报错msvcp120.dll丢失怎么办?总共有6个msvcp120.dll丢失的解决方法分享

一、msvcp120.dll是什么文件&#xff1f; msvcp120.dll是Microsoft Visual C Redistributable Package的一部分&#xff0c;它是运行许多Windows应用程序所必需的动态链接库文件之一。它包含了许多C函数和类&#xff0c;用于支持各种应用程序的正常运行。因此&#xff0c;当ms…

erlang/OTP 平台(学习笔记)(三)

分布式 Erlang 借助于语言属性和基于复制的进程通信&#xff0c;Erlang程序天然就可以分布到多台计算机上。要问为什么&#xff0c;且让我们来看两个用Java或C这类语言写成的进程&#xff0c;它们运作良好并以共享内存为通信手段。假设你已经搞定了锁的问题&#xff0c;一切精…

C语言整型常量的表示方法

整形常量就是整常数&#xff0c;在c语言中&#xff0c;使用的整常数有八进制&#xff0c;十进制和十六进制三种 1&#xff09;十进制常数&#xff1a;十进制常数没有前缀&#xff0c;其数码为0~9。 以下各数是合法的十进制整常数&#xff1a; 237、-568、65535、1627&#xf…

leetcode206.反转链表

https://leetcode.cn/problems/reverse-linked-list/description/ 题目 给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 示例 1&#xff1a; 输入&#xff1a;head [1,2,3,4,5] 输出&#xff1a;[5,4,3,2,1]示例 2&#xff1a; 输入&am…

中国政企客户,需要什么样的云服务?

0. 前言和目录 我前段时间写了一篇《技术服务工作的呼吁和推演》&#xff0c;文中感叹&#xff0c;几乎没有云厂商重视技术服务工作。很意外也很庆幸&#xff0c;这篇文章起到了抛砖引玉的效果&#xff0c;我收到了一些高价值反馈。我的感叹有些肤浅&#xff0c;国内政企云行业…

ssm基于Vue的健身房会员管理系统+vue论文

摘 要 互联网发展至今&#xff0c;无论是其理论还是技术都已经成熟&#xff0c;而且它广泛参与在社会中的方方面面。它让信息都可以通过网络传播&#xff0c;搭配信息管理工具可以很好地为人们提供服务。针对信息管理混乱&#xff0c;出错率高&#xff0c;信息安全性差&#x…

【车载开发系列】AutoSar当中的DcmDspSecurity容器

【车载开发系列】AutoSar当中的DcmDspSecurity容器 AutoSar当中的DcmDspSecurity容器 【车载开发系列】AutoSar当中的DcmDspSecurity容器一. DcmDspSecurity容器位置二. 关于对安全等级理解三. 关于安全等级的定义1&#xff09;Extendedsecuritylevel2&#xff09;Programmings…

软件设计不是CRUD(10):低耦合模块设计理论——业务抽象:从需求中提取业务维度

接上文《软件设计不是CRUD(9):低耦合模块设计理论——设计落地所面临的挑战》 2、什么是业务抽象 业务抽象是一种将需求落地成模块功能的设计思想,是对业务需求和技术设计进行转换、隔离的一种分析方法。经过业务抽象后的业务模块一般具有较高的业务屈服度,能更大程度满…

Envoy

一、Envoy简介 Envoy 是一款由Lyft开源的高性能服务代理软件&#xff0c;使用现代C语言&#xff08;C11及C14&#xff09;开发&#xff0c;提供四层和七层网络代理功能。2017年&#xff0c;Envoy 被捐赠给 CNCF 基金会&#xff0c;最终成为继Kubenetes利Prometheus 之后第3个 …

vue -- 单页面应用和多页面应用区别及优缺点

Vue单页面应用&#xff08;SPA&#xff09;和多页面应用&#xff08;MPA&#xff09;是两种常见的前端应用架构模式&#xff0c;它们在开发方式、性能以及用户体验方面有着不同的特点。 单页面应用&#xff08;SPA&#xff09;&#xff1a; SPA 是一种基于JavaScript的应用程序…

EI级 | Matlab实现VMD-TCN-BiLSTM变分模态分解结合时间卷积双向长短期记忆神经网络多变量光伏功率时间序列预测

EI级 | Matlab实现VMD-TCN-BiLSTM变分模态分解结合时间卷积双向长短期记忆神经网络多变量光伏功率时间序列预测 目录 EI级 | Matlab实现VMD-TCN-BiLSTM变分模态分解结合时间卷积双向长短期记忆神经网络多变量光伏功率时间序列预测预测效果基本介绍程序设计参考资料 预测效果 基…

【AUTOSAR】RTE的基础概念和ETAS ISOLAR RTA-CAR配置指南(一)RTE简介

目录 前言 RTE简介 什么是RTE 软件组件 类型 组件类型和实例

Vue3-46-Pinia-获取全局状态变量的方式

使用说明 在 Pinia 中&#xff0c;获取状态变量的方式非常的简单 &#xff1a; 就和使用对象一样。 使用思路 &#xff1a; 1、导入Store&#xff1b;2、声明Store对象&#xff1b;3、使用对象。 在逻辑代码中使用 但是 Option Store 和 Setup Store 两种方式定义的全局状态变量…

检测射线与球体交点数量代码实现(C#代码Unity环境下测试通过)

上代码&#xff1a; int RayCrossSphere(Ray ray, Sphere sphere) {Vector3 originT0Center sphere.center - ray.origin;float sqrtRadius sphere.radius * sphere.radius;if (originT0Center.sqrMagnitude < sqrtRadius){return 1;}else{Vector3 project Vector3.Proj…

7 认证相关

认证相关 7 认证相关今日详细1. 代码整合2.通用认证组件2.1 处理访问记录2.2 登录之后才具有评论和发布 3.随意的接口结论&#xff1a;在serializer中可以调用request4.完善详细页面 总结1. 小程序1.1 申请账号APPID1.2 搭建开发者工具1.3 目录结构1.4 组件1.5 微信API1.6 事件…

全新小白菜QQ云端机器人登录系统源码 /去除解密授权学习版源码

源码介绍&#xff1a; 全新小白菜QQ云端机器人登录系统源码&#xff0c;是一款经过全面解密的授权学习版源码。 这款源码已解除了授权版的限制&#xff0c;然而许多人可能对其用途并不了解。实际上&#xff0c;该源码主要面向群机器人爱好者设计。它是一个基于挂机宝机器人框…