下载phpexcel,将phpexcel导入到框架中
在GitHub中下载PHPExcel源代码到本地。https://github.com/PHPOffice/PHPExcel.git
复制PHPExcel\Classes里的文件到thinkphp框架目录:ThinkPHP\Library\Org\Util,将文件PHPExcel.php修改为PHPExcel.class.php,thinkphp框架格式,方便框架引用。如图:
image
/**
* @param $data 数据,多维数组模式。第一行为标题
$data=array(
['日期','展示量','点击量','价格','ecpm'],
['2018-06-30','10','1','1','100'],
['2018-07-01','20','2','5','500'],
['2018-07-02','1','1','1','100'],
['2018-07-03','3','1','1','100'],
);
* @param $filename 文件名
* @param $SheetTitle sheet名称
*/
public function excel_export($data,$filename="excelfile",$SheetTitle='Sheet1'){
if(empty($data)){
exit("数据为空,导出错误");
}
/*设置文件信息*/
import("Org.Util.PHPExcel");
import("Org.Util.PHPExcel.Reader.Excel2007");
$filename=str_replace('.xls', '', $filename).'.xls';
$phpexcel = new \PHPExcel();
$phpexcel->getProperties()
->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$phpexcel->getActiveSheet()->fromArray($data);
$phpexcel->getActiveSheet()->setTitle($SheetTitle);
$phpexcel->getActiveSheet()->getStyle("A1:Z1")->getFont()->setName("微软雅黑")->setSize(10)->setBold(true);//设置单元格范围的字体、字体大小、加粗
// $phpexcel->getActiveSheet()->getStyle("A1:Z1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('#00FF00');
$phpexcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objwriter = \PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
$objwriter->save('php://output');
exit;
}
传入正确参数,导出excel格式如下图:
图中数据仅为示例,数据未做严谨匹配
网友评论