方法:
public function simple_export_excel(array $table_head = array(), array $data = array(), array $exclude = array(), $file_name = 'excel', $download = 1, $sheet_name = 'sheet') {
App::import('Vendor', 'PHPExcel/PHPExcel/IOFactory');
App::import('Vendor', 'PHPExcel/PHPExcel');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()
->setCreator("admin")
->setLastModifiedBy("admin")
->setTitle("Office 2007 XLSX Record Document" )
->setSubject("Office 2007 XLSX Record Document" )
->setDescription("Record document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("export file");
$objPHPExcel->setActiveSheetIndex(0);
$activeSheet = $objPHPExcel->getActiveSheet();
$objPHPExcel->getActiveSheet()->freezePane('A2');
$activeSheet->setTitle($sheet_name);
$column = ord('A');
foreach ($table_head as $k=>$v) {
$activeSheet->getStyle(chr($column)."1")->getFont()->setSize(13);
$activeSheet->getStyle(chr($column)."1")->getFont()->setBold(true);
$chars = strlen($v);
$activeSheet->getColumnDimension(chr($column))->setWidth($chars*2);
$activeSheet->setCellValue(chr($column)."1", $v);
$activeSheet->getStyle(chr($column))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$column++;
}
$column = ord('A');
foreach ($data as $row=>$col) {
$i=0;
foreach ($col as $k=>$v ) {
if (!in_array($k, $exclude) || empty($exclude)) {
$activeSheet->setCellValue(chr($column+$i).($row+2), $v);
$i++;
}
}
}
$file_name .= date('Ymd_His') . '.xlsx';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
if ($download) {
ob_start();
$objWriter->save('php://output');
$xlsData = ob_get_contents();
ob_end_clean();
$data = [
'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData),
'name' => $file_name
];
return $this->responseJsonResult($data);
}else{
$file_path = WWW_ROOT . "xxx/xx/" . $file_name;
$objWriter->save($file_path);
return $file_path;
}
}
调用:
if ($post_request && $action == 'xxx') {
$this->autoRender = false;
$title = [
'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx'
];
$g_Excels = $g_Commons->GlobalController('xxx');
$exclude = [
'xxx',
'xxx',
'xxx',
'xxx',
'xxx',
];
return $g_Excels->simple_export_excel($title, $orders, $exclude, 'xxx');
}
前端:
var page = $("#export_req").attr('url');
$("#export_req").click(function(){
$.ajax({
url:page,
type:"POST",
async:false,
dataType:"json",
data:$("form").serialize(),
timeout:3000,
success:function(data){
var $a = $("<a>");
$a.attr("href",data.datas.file);
$("body").append($a);
$a.attr("download", data.datas.name);
$a[0].click();
$a.remove();
},
error:function(){
console.log(data);
}
});
});