【thinkphp】最简单的tp5集成phpexcel导出excel

 

tp5集成phpexcel,导出最简单的表格

最近用tp5框架,在网上找了很多集成phpexcel的方法,导出都会报错。自己整理了一个集成方法,导出最简单的excel文件。

一、首先将下载的phpexcel库,放到项目的extend文件夹下面

    下载地址:

    http://www.codeplex.com/PHPExcel

blob.png

二、controller中下载方法的注意事项

    blob.png

blob.png

三、完整的下载方法。

 
public function exportExcel(){
        ini_set('memory_limit', '1024M');//设置php允许的文件大小最大值
        Loader::import('PHPExcel.Classes.PHPExcel');//必须手动导入,否则会报PHPExcel类找不到
        $objPHPExcel = new \PHPExcel();
        $worksheet = $objPHPExcel->getActiveSheet();
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
// Set document properties
        $objPHPExcel->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");
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '昵称')
            ->setCellValue('B1', '链接')
            ->setCellValue('C1', '房间号')
            ->setCellValue('D1', '分组');
// Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.date('Ymd').'.xlsx"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
        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($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
 
(注:将下载的phpexcel库,直接放到web根目录,
然后直接访问example里面的php文件,就会下载相应模板的excel,然后找到对应的excel模板,
对照着代码,就可以看懂phpexcel是怎么用的了)

blob.png

进入phpexcel库的example文件夹,下面有很多导出的demo

blob.png

直接访问01simple.php,会发现直接开始下载了,并且会返回相应的信息

blob.png

可以看到提示我们,文件已经被创建,我们就去这个目录下面看一下

blob.png

果然,excel已经生成好了,两个文件是因为,php文件用了两种格式导出,我们选择一个适合的使用就行了

blob.png

点击跳转原文地址:http://www.dabook.top/blog/6.html

猜你喜欢

转载自blog.csdn.net/qq_35159277/article/details/80781041