最近在开发微信小程序商城的过程中,后端遇到了需要根据条件导出订单的需求。
查询PHPExcel已经停止维护了,于是改用了Spreadsheet的composer。
composer require phpoffice/phpspreadsheet
查询时间条件使用了Carbon 的composer。
composerrequirenesbot/carbon
$cauthIden是我设置的唯一标识符,用来区分小程序对应的用户,具有唯一性。
具体操作如下
先引入Spreadsheet与Carbon
```
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \Carbon\Carbon;
function getMonthData($date,$cauthIden)
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$orderData = $this->model . 'ShopOrder';
$first = strtotime($date);
$dates = explode('-',$date); //拆分post的日期,2018-05-18 变成数组date[0]=>2018,date[1]=>05....
$carbon = Carbon::create($dates[0],$dates[1],$dates[2],00,00);
$lastDay = $carbon->endOfMonth(); //该月最后一天
$lastDay = strtotime($lastDay); //转成时间戳
$parameters = "status = 0 and cauth_iden = '".$cauthIden."' and dates >".$first.' and dates < '.$lastDay; //查询当前月份开始
$order = $orderData::find( $parameters )->toArray();
$title = ['uid'=>'用户编号', 'trade_sn'=>'订单号','total_price'=>'总金额','express_status'=>'订单状态',
'nickName'=>'用户名', 'dates'=>'购买时间', 'status'=>'状态'];
$sheet->setCellValue('A1', $title['uid']);
$sheet->setCellValue('B1', $title['nickName']);
$sheet->setCellValue('C1', $title['trade_sn']);
$sheet->setCellValue('D1', $title['total_price']);
$sheet->setCellValue('E1', $title['dates']);
$sheet->setCellValue('F1', $title['express_status']);
$i = 2;
foreach ($order as $key )
{
//查询uid对应的用户名,金额除以100
$usersData = $this->model.'Users';
$users = $usersData::find("status = 0 and id = ".$key['uid'])->toArray();
foreach($users as $k)
{
$sheet->setCellValue('A'.$i, $key['uid']);
$sheet->setCellValue('B'.$i, $k['nickName']);
$sheet->setCellValue('C'.$i, $key['trade_sn']);
$sheet->setCellValue('D'.$i, date('Y-m-d H:i:s',$key['dates']));
$sheet->setCellValue('E'.$i, $key['total_price']/100);
$sheet->setCellValue('F'.$i, $key['express_status'] == 0 ?'未发货' :($key['express_status'] == 1?'已发货':'已签收'));
$i++;
}
//
}
// foreach($user as $key)
// {
// $sheet->setCellValue('A'.$i, $key['id']);
// $sheet->setCellValue('B'.$i, $key['openId']);
// $sheet->setCellValue('C'.$i, $key['reg_time']);
// $sheet->setCellValue('D'.$i, $key['status']);
//
// $i++;
// }
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename='.date('Ymd').uniqid().".xlsx");
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit();
}
```
网友评论