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

相关推荐
CodeCraft Studio12 分钟前
国产化Excel处理组件Spire.XLS教程:如何使用 C# 将 Excel(XLS 或 XLSX)文件转换为 PDF
pdf·c#·excel
CYRUS_STUDIO19 分钟前
攻防 FART 脱壳:特征检测识别 + 对抗绕过全解析
android·安全·逆向
aningxiaoxixi33 分钟前
android 媒体框架之MediaCodec
android·网络·媒体
二流小码农1 小时前
鸿蒙开发:应用内如何做更新
android·ios·harmonyos
霸王蟹2 小时前
React 项目中封装 Excel 导入导出组件:技术分享与实践
前端·笔记·学习·react.js·typescript·excel·vite
废材是怎么养成的2 小时前
SpringBatch+Mysql+hanlp简版智能搜索
mysql
兰琛2 小时前
Compose仿微信底部导航栏NavigationBar :底部导航控制滑动并移动
android·android jetpack
字节源流2 小时前
【MYSQL】索引篇(一)
数据库·mysql
n33(NK)2 小时前
MySQL中count(1)和count(*)的区别及细节
数据库·mysql
wzj_what_why_how3 小时前
Kotlin JVM 注解详解
android·kotlin