ThinkPHP6.0 导出 Excel 案例

831 阅读1分钟

(一)环境配置

基础环境

  • PHP7.4.4
  • MySQL8.0.19
  • Nginx1.16.1
  • 系统环境:Windows10 x64
  • PHP 集成环境:phpEnv7.1.5(www.phpenv.cn/
  • 数据库管理工具:Navicat Premium 15.0.11
  • PHP 依赖管理工具:Composer(getcomposer.org/Compo...

(二)安装 ThinkPHP6.0 并配置

(1)安装 ThinkPHP6.0

composer create-project topthink/think tp2excel

(2)安装 Excel 插件 phpspreadsheet

composer require phpoffice/phpspreadsheet

(3)配置站点

attachments-2020-12-4X7gbqTU5fe4024cd1931.jpg

(4)配置 Nginx 重写

attachments-2020-12-BaGvqMSl5fe40255373f6.jpg

(5)启动,查看首页

attachments-2020-12-bC9bqRws5fe4025c83b70.jpg

(三)配置数据库与数据库设计

(1)数据库配置

attachments-2020-12-6cQOwNGl5fe40264c2c27.jpg

(2)数据库建表(略)

(四)查询 SQL 数据并导出

(1)引入 Spread.php 插件

attachments-2020-12-IQEPlORz5fe4026e7a770.jpg

(2)查询数据并导出

<?php
namespace appcontroller;
use appBaseController;
use thinkfacadeDb;
use ToolsSpread;
class Index extends BaseController
{
 public function index()
{
 return '<html><a href="/index/excel.html?limit=2000">导出Excel</a><html>';
 }
 public function excel($limit = 10)
{
 $expTableData = Db::table('b_demo')->limit($limit)->select();
 $fileName = "IP地址导出";
 $Excel['fileName']=$fileName.date('Y年m月d日-His',time());//or $xlsTitle
 $Excel['cellName']=['A','B','C','D'];
 $Excel['H'] = ['A'=>12,'B'=>22,'C'=>28,'D'=>38];//横向水平宽度
 $Excel['V'] = ['1'=>40,'2'=>26];//纵向垂直高度
 $Excel['sheetTitle']=$fileName;//大标题,自定义
 $Excel['xlsCell']=[
 ['id','编号'],
 ['start','开始IP'],
 ['end','结束IP'],
 ['disp','地区']];
 Spread::excelPut($Excel,$expTableData);
 }
}

(3)导出结果

attachments-2020-12-B0QQBoeA5fe4027711419.jpg

原文:learnku.com/articles/42…