1.添加按钮,并传参
<a href="{:url('goods/exportGoods')}?status={$goodsStatus}"
class="btn btn-darkorange btn-sm shiny">
<i class="fa fa-list"></i> 导出订单
</a>
2.列表页接收数据,并渲染到视图
$status = 'all'; //要导出的表的状态,默认导出所有订单
$getDate = input('get.');
if (isset($getDate['status'])) { //如果$getDate['status']存在,就把他赋值给$status
$status = $getData['status'];
}
$this->assign([
'goodsStatus' => $status, //渲染到视图
]);
3.定义导出订单的方法
//导出商品表
public function exportGoods()
{
//APP_PATH public/index.php中设置
$phpexcelSrc = APP_PATH.'../plus/PHPexcel/PHPExcel.php'; //PHPexcel路径
include($phpexcelSrc); //引入
$phpexcel = new \PHPExcel(); //实例化
$phpexcel->setActiveSheetIndex(0); //第一张表
$sheet = $phpexcel->getActiveSheet(); //获取到第一张表的资源句柄
$getDate = input('get.'); //接收穿过来的数据
if (isset($getDate['status'])) { //如果$getDate这个函数存在
$status = $getDate['status']; //就赋值给$status
}
if (!isset($where)) { //如果$where不存在,就给他一个默认值
$where = 1;
}
$join = [ //管理表
['category c','g.category_id=c.id'],
['brand b','g.brand_id=b.id','LEFT'],
['type t','g.type_id=t.id','LEFT'],
['product p','g.id=p.goods_id','LEFT'],
];
//查询goods表需要的字段
$goodsRes = db('goods')->alias('g')->field('g.*,c.name as cname,b.name as bname,t.type_name,SUM(p.goods_number) gn')->where($where)->
join($join)->group('g.id')->order('g.id desc')->select();
//表格第一行标题
$arr = [
'id'=>'商品id',
'name'=>'名称',
'code'=>'编号',
'describe'=>'描述',
'og_thumb'=>'缩略图',
'markte_price'=>'市场价',
'shop_price'=>'售卖价',
'on_sale'=>'是否上架',
'cname'=>'所属栏目',
'bname'=>'品牌',
'type_name'=>'所属类型',
'weight'=>'重量',
'weight_unit'=>'单位',
'gn'=>'库存',
];
// 把标题插入到第一行
array_unshift($goodsRes,$arr); //array_unshift() 函数用于向数组插入新元素。新数组的值将被插入到数组的开头。
$row = 0; //每插入一行加一
foreach ($goodsRes as $k => $v) {
//每循环一次加一
$row += 1;
//把表中单选字段,改为中文
if ($v['on_sale']==1) {
$v['on_sale'] = '上架';
}else{
$v['on_sale'] = '下架';
}
if ($k) { //$k不是第一条,才执行,因为第一次循环是标题
$v['create_time'] =date("Y-m-d H:i:s",$v['create_time']); //时间戳转换为时间格式
}
//表格每列数据
$sheet->setCellValue('A'.$row,$v['id'])
->setCellValue('B'.$row,$v['name'])
->setCellValue('C'.$row,$v['code'])
->setCellValue('D'.$row,$v['describe'])
->setCellValue('E'.$row,$v['og_thumb'])
->setCellValue('F'.$row,$v['markte_price'])
->setCellValue('G'.$row,$v['shop_price'])
->setCellValue('H'.$row,$v['on_sale'])
->setCellValue('I'.$row,$v['cname'])
->setCellValue('J'.$row,$v['bname'])
->setCellValue('K'.$row,$v['type_name'])
->setCellValue('L'.$row,$v['weight'])
->setCellValue('M'.$row,$v['weight_unit'])
->setCellValue('N'.$row,$v['gn']);
}
// 头部信息
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="goods.xlsx'); //表的命名
header('Cache-Control: max-age=0');
$phpwriter = new \PHPExcel_Writer_Excel2007($phpexcel);
$phpwriter->save('php://output');
}