在 ThinkPHP 5.1 中引入 PHPExcel(现在已被官方弃用,推荐使用 PhpSpreadsheet)时,可以按照以下步骤进行操作:
- 在
composer.json
文件中添加 PHPExcel(PhpSpreadsheet)的依赖项。找到require
部分,并添加以下行:"require": {"phpoffice/phpspreadsheet": "^1.0" }
-
运行命令
composer update
来安装依赖项。composer require phpoffice/phpexcel
安装成功即可存在该目录/vendor/phpoffice/
3、引入类
use PHPExcel;
use PHPExcel_IOFactory;
<?phpnamespace app\api\controller;use Home\Controller\HeyteaApiController;
use Home\Controller\TelMsgAliController;
use think\Controller;
use think\Db;
use think\db\Connection;
use think\facade\Cache;use PHPExcel;
use PHPExcel_IOFactory;//引入两个类require_once '../php-sdk/youzanyun_open_sdk/open-sdk/vendor/autoload.php';class Index extends Controller
{
public function excel(){set_time_limit(0);//设置PHP超时时间$data_res = Db::name("hb_prize_record")->where('pz_type', '实物')->field("id,mark,is_get,get_time,tel,pz_title,pz_name,time,user_name,user_tel,user_procity,user_address,user_time")->select();
// return json($data_res);$path = dirname(__FILE__);//找到当前脚本所在路径$PHPExcel = new \PHPExcel();//实例化phpexcel$PHPSheet = $PHPExcel->getActiveSheet();$PHPSheet->setTitle("实物中奖信息");//设置表内部名称$PHPSheet->setCellValue("A1", "表编号")->setCellValue("B1", "活动类型")->setCellValue("C1", "是否领取(1-已领取,0-未领取)")->setCellValue("D1", "领取时间")->setCellValue("E1", "登录号码")->setCellValue("F1", "奖项名称")->setCellValue("G1", "中奖时间")->setCellValue("H1", "收货姓名")->setCellValue("I1", "收货电话")->setCellValue("J1", "省市区")->setCellValue("K1", "详细地址")->setCellValue("L1", "提交时间");//表格数据$num = 2;//数据foreach ($data_res as $k => $v) {$PHPSheet->setCellValue("A" . $num, $v['id']);$PHPSheet->setCellValue("B" . $num, $v['mark']);$PHPSheet->setCellValue("C" . $num, $v['is_get']);$PHPSheet->setCellValue("D" . $num, $v['get_time']);
// $v['now_time'] = date("Y-m-d H:i", $v['now_time']);$PHPSheet->setCellValue("E" . $num, $v['tel']);$PHPSheet->setCellValue("F" . $num, $v['pz_title']);$PHPSheet->setCellValue("G" . $num, $v['pz_name']);$PHPSheet->setCellValue("H" . $num, $v['time']);$PHPSheet->setCellValue("I" . $num, $v['user_name']);$PHPSheet->setCellValue("J" . $num, $v['user_procity']);$PHPSheet->setCellValue("K" . $num, $v['user_address']);$PHPSheet->setCellValue("L" . $num, $v['user_time']);$num++;}$PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");//创建生成的格式header('Content-Disposition: attachment;filename="实物中奖信息.xlsx"');//下载下来的表格名header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');$PHPWriter->save("php://output");//表示在$path路径下面生成demo.xlsx文件exit;}
}
注意事项:
1、如果本地能导出excel并可以正常打开,但上传到服务器就不行,提示无法打开文件,试试在末尾加上 exit;如
$PHPWriter->save("php://output");//表示在$path路径下面生成demo.xlsx文件
exit;
2、如果是导出文件提示不存在,或者浏览器直接什么都不显示,这个时候考虑是不是没清空缓冲区;
缓冲区问题 解决方法:ob_end_clean() 在输出文件之前先清空缓冲