ThinkPhp5-PHPExcel导出数据
Posted 远离油腻人间!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThinkPhp5-PHPExcel导出数据相关的知识,希望对你有一定的参考价值。
php-Excel
标签(空格分隔): php
类库下载地址:https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8
php导出excel表格数据的基本实现
实现步骤:
1 把文件夹放到extend目录下
2 import助手函数导入类
3 设置excel表头
4 填充数据
注意事项:
1 数据从第二行开始填充
ThinkPHP5示例:
# 公共方法
public function phpExcel($title, $list, $fileName)
{
import(‘PHPExcel.Classes.PHPExcel‘);
import(‘PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory‘);
$PHPExcel = new PHPExcel;
$PHPSheet = $PHPExcel->getActiveSheet();
foreach ($list as $k => $v) {
# code...
foreach ($title as $key => $value) {
if ($k == 0) {
$PHPSheet->setCellValue($key.‘1‘, end($value));
}
$i = $k + 2;
$PHPSheet->setCellValue($key.$i, $v[reset($value)]);
}
}
$PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");;
header(‘Content-Disposition:attachment;filename=‘.$fileName.‘.xlsx‘);
header("Content-Transfer-Encoding:binary");
$PHPWriter->save("php://output");
}
# 调用方法:
public function main()
{
$title = [
‘A‘ => [‘id‘, ‘ID‘],
‘B‘ => [‘nickname‘, ‘昵称‘],
‘C‘ => [‘phone‘, ‘手机号‘],
‘D‘ => [‘avatar‘, ‘头像‘],
‘E‘ => [‘profile‘, ‘个人签名‘],
‘F‘ => [‘token‘, ‘用户唯一标识‘],
‘G‘ => [‘sex‘, ‘性别‘],
‘H‘ => [‘status‘, ‘状态‘],
‘I‘ => [‘to_host‘, ‘主办方id‘]
];
$field = ‘id, nickname, phone, avatar, profile, token, sex, status, to_host‘;
$list = Db::table(‘t_user‘)->field($field)->limit(10)->select();
$fileName = ‘测试‘.date(‘Y-m-d‘);
$this->excel($title, $list, $fileName);
}
以上是关于ThinkPhp5-PHPExcel导出数据的主要内容,如果未能解决你的问题,请参考以下文章