public function test(){
$xlsName = "测试";
//注意 数组第一个字段必须是小写 数组第二个(列标题)根据你的情况填写
$xlsCell = array(
array('number','单号'),
array('totalNum','采购总数量'),
array('dataAmount','单据金额'),
array('actualAmount','实际金额'),
array('createTime','生成时间')
);
$xlsModel = new ReinsurancePolicy();
$xlsData = $xlsModel->Field('number,totalNum,dataAmount,actualAmount,createTime')->select()->toArray();
$this->exportExcel($xlsName,$xlsCell,$xlsData);
}
function export_excel($expTitle,$expCellName,$expTableData)
{
$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
$fileName = $expTitle ;//or $xlsTitle 文件名称可根据自己情况设定
$cellNum = count($expCellName);
$dataNum = count($expTableData);
$objPHPExcel = new PHPExcel();//方法一
$cellName = array('A','B', 'C','D', 'E', 'F','G','H','I', 'J', 'K','L','M', 'N', 'O', 'P', 'Q','R','S', 'T','U','V', 'W', 'X','Y', 'Z', 'AA',
'AB', 'AC','AD','AE', 'AF','AG','AH','AI', 'AJ', 'AK', 'AL','AM','AN','AO','AP','AQ','AR', 'AS', 'AT','AU', 'AV','AW', 'AX',
'AY', 'AZ');
//设置头部导出时间备注
$objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . ' 导出时间:' . date('Y-m-d H:i:s'));
//设置列名称
for ($i = 0; $i < $cellNum; $i++) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
}
//赋值
for ($i = 0; $i < $dataNum; $i++) {
for ($j = 0; $j < $cellNum; $j++) {
$objPHPExcel->getActiveSheet(0)->setCellValue(
$cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]
);
}
}
ob_end_clean();//这一步非常关键,用来清除缓冲区防止导出的excel乱码
header('pragma:public');
header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
$objWriter = PHPExcel_IOFactory::createWriter(
$objPHPExcel, 'Excel5'
);//"Excel2007"生成2007版本的xlsx,"Excel5"生成2003版本的xls
$objWriter->save('php://output');
}