下面是我利用PHPExcel导出数据到excel的一次实践。
第一步,当然是到PHPExcel官网去下载phpexcel插件,把Class 改名为 phpExcel 单独拿出 将其放到thinkphp的vendor目录下。
第二,将到入数据的具体逻辑封装到工具类中。具体逻辑代码如下:
class UntilLogic
{
public function phpExcelList($field, $list, $title='文件')
{
vendor('phpExcel.PHPExcel');
$objPHPExcel = new \PHPExcel();
$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //设置保存版本格式
foreach ($list as $key => $value) {
foreach ($field as $k => $v) {
if ($key == 0) {
$objPHPExcel->getActiveSheet()->setCellValue($k . '1', $v[1]);
}
$i = $key + 2; //表格是从2开始的
$objPHPExcel->getActiveSheet()->setCellValue($k . $i, $value[$v[0]]);
}
}
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='.$title.'.xls');
header("Content-Transfer-Encoding:binary");
// $objWriter->save($title.'.xls');
$objWriter->save('php://output');
}
}
第三步,读取需要下载数据,和组合excel数据标题$field参数,直接调用第二步的方法。
public function outExcelRecharge() {
$where = "1=1";
$data = $dbEngin->field('transactions.*,u.name as uname, k.name as kname')->where($where)->order('id desc')->select();
foreach ($data as $key => $value) {
$data[$key]['price'] = number_format($data[$key]['price']/100,2);
$data[$key]['uname'] = filterEmoji($value['uname']);
}
$field = array(
'A' => array('id', 'ID'),
'B' => array('user_id', '用户ID'),
'C' => array('uname', '用户名称'),
'D' => array('created', '时间'),
'E' => array('order_id', '订单号'),
'F' => array('price', '金额(元)'),
'G' => array('coins', '充值金币数'),
'H' => array('device_id', '设备ID'),
'I' => array('ktv_id', 'ktvID'),
'J' => array('kname', 'ktv名称'),
'K' => array('status', '状态(paid:已付款,refunded:已退款,pending:处理中)')
);
$until = new UntilLogic();
$until->phpExcelList($field, $data, '充值列表_' . date('Y-m-d'));
}
以上就是比较常见也非常简单的phpexcle数据到出方式。