tp8读取mysql导出excel

环境:php8.3, thinkphp8.0, mysql8.0

php 复制代码
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use think\facade\Db;
use think\response\Json;

class Index
{
    public function index(): Json
    {
        // 查询 MySQL 数据表数据
        $employees = Db::name('employee')
            ->field('emp_name, emp_sex, emp_phone, create_time')
            ->select()
            ->toArray();

        // 创建 PhpSpreadsheet 对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $sheet->setCellValue('A1', '姓名');
        $sheet->setCellValue('B1', '性别');
        $sheet->setCellValue('C1', '电话');
        $sheet->setCellValue('D1', '日期');

        // 设置表头样式:居中对齐和加粗
        $headerStyle = [
            'font' => [
                'bold' => true,  // 加粗
                'size' => 12,    // 字体大小
            ],
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER,  // 水平居中
                'vertical' => Alignment::VERTICAL_CENTER,      // 垂直居中
            ]
        ];

        // 应用样式到表头
        $sheet->getStyle('A1:D1')->applyFromArray($headerStyle);

        // 填充数据
        $rowNum = 2;  // 从第二行开始填充数据
        foreach ($employees as $employee) {
            $sheet->setCellValue('A' . $rowNum, $employee['emp_name']);
            $sheet->setCellValue('B' . $rowNum, $employee['emp_sex']);
            $sheet->setCellValue('C' . $rowNum, $employee['emp_phone']);
            $sheet->setCellValue('D' . $rowNum, $employee['create_time']);
            $rowNum++;
        }

        /*$writer = new Xlsx($spreadsheet);
        $writer->save('demo.xlsx');*/
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="myfile.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        return json(['code'=>200,'msg'=>'success']);
    }
}
bash 复制代码
composer require phpoffice/phpspreadsheet

根据phpspreadsheet官方文档,写了上述代码,如有不懂的地方,请查阅官方文档。

相关推荐
bing_1582 小时前
Excel 如何进行多条件查找或求和?
excel
秀儿还能再秀2 小时前
基于Excel的数据分析思维与分析方法
数据分析·excel
bing_1582 小时前
Excel 如何处理更复杂的嵌套逻辑判断?
excel
weixin_472339462 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
灵犀学长2 小时前
EasyExcel之SheetWriteHandler:解锁Excel写入的高阶玩法
spring boot·excel
tan180°4 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
哲科软件5 小时前
跨平台开发的抉择:Flutter vs 原生安卓(Kotlin)的优劣对比与选型建议
android·flutter·kotlin
DuelCode5 小时前
Windows VMWare Centos Docker部署Springboot 应用实现文件上传返回文件http链接
java·spring boot·mysql·nginx·docker·centos·mybatis
幽络源小助理5 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
爬山算法7 小时前
MySQL(116)如何监控负载均衡状态?
数据库·mysql·负载均衡