时间:2024-06-16
以下是使用 ThinkPHP 实现将数据写入 Excel 并导出的示例代码:
首先确保已经安装了 phpoffice/phpexcel 扩展。
<?php
namespace app\controller;
use think\Controller;
use PHPExcel;
use PHPExcel_IOFactory;
class ExcelController extends Controller {
public function exportData() {
// 模拟一些数据
$data = [
['id' => 1, 'name' => '张三'],
['id' => 2, 'name' => '李四'],
['id' => 3, 'name' => '王五']
];
$objPHPExcel = new PHPExcel();
// 设置表头
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', '编号')
->setCellValue('B1', '姓名');
$row = 2;
foreach ($data as $item) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$row, $item['id'])
->setCellValue('B'.$row, $item['name']);
$row++;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="data.xlsx"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
}
}
Copyright © 2019-2024 2543.cn