您的当前位置:首页 > 知识博客 > 建站经验

Thinkphp实现excel数据写入并导出

时间: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');
}
}


欢迎咨询/Welcome to inquire
tel/vx:18842938855
qq:1685522781
email:1685522781@qq.com

Copyright © 2019-2024 sex.cyou


Whatsapp