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官方文档,写了上述代码,如有不懂的地方,请查阅官方文档。

相关推荐
2501_9151063222 分钟前
iOS 应用加固与苹果软件混淆指南,如何防止 IPA 被反编译与二次打包?
android·ios·小程序·https·uni-app·iphone·webview
Java水解1 小时前
MySQL 中 ROW_NUMBER() 函数详解
后端·mysql
枫,为落叶1 小时前
【vue】导出excel
前端·vue.js·excel
huibin1478523691 小时前
不能识别adb/usb口记录
android·adb
星空的资源小屋2 小时前
RoboIntern,一款自动化办公小助手
运维·人工智能·pdf·自动化·电脑·excel
黄林晴3 小时前
Kotlin 2.3.0-Beta1 重磅发布:这些新特性让代码更安全、更高效!
android·kotlin
2501_915921434 小时前
iOS 应用加固与苹果软件混淆全解析 IPA 文件防反编译、混淆加密与无源码加固策略
android·macos·ios·小程序·uni-app·cocoa·iphone
君逸臣劳4 小时前
玩Android Harmony next版,通过项目了解harmony项目快速搭建开发
android·harmonyos
帅锅锅0074 小时前
Android.bp 指南
android