php使用phpexcel导出文件

 首先需要去官网https://github.com/PHPOffice/PHPExcel/下载PHPExcel

代码如下:



<?php
date_default_timezone_set('PRC');
/**
* 导出提现,充值记录
* */
function exportWalletStatAction(){
$body = [
[
'order_id'=>1,
'money'=>2222,
],
[
'order_id'=>2,
'money'=>3333,
]
];

$head = [['订单号', '金额']];
$needField = ['order_id','money'];
$body = filterFiels($body,$needField);
//导出文件的数据
$fileName = 'test';
export($fileName, $head, $body);
}
/**
* 得到需要导出的字段
* @return string
*/
function filterFiels($body, $needField)
{
if (!is_array($body) || !count(array($body))) {
$this->export();
}
$exportData = [];
if (is_array($body) && count($body)) {
foreach ($body as $key => $val) {
foreach ($needField as $needVal) {
if(isset($val[$needVal])){
$exportData[$key][$needVal] = $val[$needVal];
}
}
}
}
return $exportData;
}

/**
* 处理导出文件
* @param string $fileName
* @param string $head
* @param string $body
* @param bool $clear
*/
function export($fileName = '', $head = '', $body = '', $clear = false)
{
if (!is_array($body) || !count(array($body)) || empty($body) ) {
$body = [
[
'没有相关数据'
]
];
}
if (is_array($head) && count($head)) {
$data = array_merge($head, $body);
} else {
$data = $body;
}
if (!$fileName) {
$fileName = date('ymdHis');
} else {
if (!$clear) {
$fileName = $fileName . '_' . date('ymdHis');
}
}
$fileName .= '.xls';
foreach ($data as $key => $val) {
foreach ($val as $k => $v) {
if (strpos($v, '=') === 0) {
$val[$k] = "\t" . $v;
$data[$key] = $val;
}
}
}
download($data, $fileName);
}

/**
* 导出文件
* @param string $fileName
* @param string $head
* @param string $body
* @param bool $clear
*/
function download($data, $fileName = 'data.xsl')
{
error_reporting(E_ALL ^ E_NOTICE);
//error_reporting(0);
//文件引入
require_once __DIR__ .'/../../../../public/js/phpexcel/Classes/PHPExcel.php';
require_once dirname(__FILE__) . '/../../../../public/js/phpexcel/Classes/PHPExcel/Writer/Excel2007.php';
$objPHPExcel = new \PHPExcel();
$objPHPExcel->getActiveSheet()->fromArray($data, null, 'A1');
$objPHPExcel->getActiveSheet()->setTitle('Sheet1');
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();
ob_start();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit();//调用$objWriter->save('php://output')之后一定要紧跟exit
}
exportWalletStatAction();