最近 遇到 需要 把 数据库 查询出的数据 导入 到 excel 表格的功能 。
准备开始,
至于怎么安装Thinkphp6 我就不介绍了, 自行去官网查看
通过 composer 安装 phpoffice/phpspreadsheet
composer require phpoffice/phpspreadsheet
如图:phpoffice/phpspreadsheet 下载好了, 该目录是 vendor/
1. 在 extend目录下 新建一个 Tools 目录 , Tools 目录新建 PHPExcel.php 文件
PHPExcel.php 写入
<?php namespace Tools; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\IOFactory; class PHPExcel { /** * 导出Excel表格 Xlsx格式(2007版) * * @author liang <23426945@qq.com> * @datetime 2019-12-22 * * @param array $title 表头单元格内容 * @param array $data 从第二行开始写入的数据 * @param string $path Excel文件保存位置,路径中的目录必须存在 * * @return null 没有设定返回值 */ static public function excelput($title,$data,$path,$filename=""){ $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // 表头单元格内容 第一行 $titCol = 'A'; foreach ($title as $value) { // 单元格内容写入 $sheet->setCellValue($titCol . '1', $value); $titCol++; } // 从第二行开始写入数据 $row = 2; foreach ($data as $item) { $dataCol = 'A'; foreach ($item as $value) { // 单元格内容写入 $sheet->setCellValue($dataCol . $row, $value); $dataCol++; } $row++; } $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save($path); } }
2. 使用方法
<?php namespace app\index\controller; use app\index\controller\Front; use think\facade\Db; use Tools\PHPExcel; class Index extends Front{ public function index(){ // 查询 id 小于 120 的数据 $res = Db::name('User')->where('id','<',120)->select(); // 表头 $title = ['牙齿症状','性别','年龄','姓名','电话','页面时间','页面来源']; // 调用方法 PHPExcel::excelput($title,$res,"./uploads/excel/06.xlsx"); } }
上面的 文件存储路径 是以 public 为基准的,