网络编程 
首页 > 网络编程 > 浏览文章

Codeigniter+PHPExcel实现导出数据到Excel文件

(编辑:jimmy 日期: 2024/10/17 浏览:3 次 )

PHPExcel是用来操作OfficeExcel文档的一个PHP类库,它基于微软的OpenXML标准和PHP语言。可以使用它来读取、写入不同格式的电子表格。而Codeigniter是一个功能强大的PHP框架。二者结合就能起到非常棒的效果啦!

1.准备工作

下载PHPExcel:http://phpexcel.codeplex.com
这是个强大的Excel库,这里只演示导出Excel文件的功能,其中的大部分功能可能都用不着。

2.安装PHPExcel到Codeigniter

1)解压压缩包里的Classes文件夹中的内容到application\libraries\目录下,目录结构如下:
--application\libraries\PHPExcel.php
--application\libraries\PHPExcel(文件夹)
2)修改application\libraries\PHPExcel\IOFactory.php文件
--将其类名从PHPExcel_IOFactory改为IOFactory,遵从CI类命名规则。
--将其构造函数改为public

3.安装完毕,写一个导出excel的控制器(Controller)

代码如下:
复制代码 代码如下:<?php
classTable_exportextendsCI_Controller{
    function__construct()
    {
        parent :: __construct();
        // Hereyoushouldaddsomesortofuservalidation
        // topreventstrangersfrompullingyourtabledata
    }
    functionindex($table_name)
    {
        $query = $this -> db -> get($table_name);
        if(!$query)
            returnfalse;
        // StartingthePHPExcellibrary
        $this -> load -> library('PHPExcel');
        $this -> load -> library('PHPExcel/IOFactory');
        $objPHPExcel = newPHPExcel();
        $objPHPExcel -> getProperties() -> setTitle("export") -> setDescription("none");
        $objPHPExcel -> setActiveSheetIndex(0);
        // Fieldnamesinthefirstrow
        $fields = $query -> list_fields();
        $col = 0;
        foreach($fieldsas$field)
        {
            $objPHPExcel -> getActiveSheet() -> setCellValueByColumnAndRow($col, 1, $field);
            $col++;
            }
        // Fetchingthetabledata
        $row = 2;
        foreach($query -> result()as$data)
        {
            $col = 0;
            foreach($fieldsas$field)
            {
                $objPHPExcel -> getActiveSheet() -> setCellValueByColumnAndRow($col, $row, $data -> $field);
                $col++;
                }
            $row++;
            }
        $objPHPExcel -> setActiveSheetIndex(0);
        $objWriter = IOFactory :: createWriter($objPHPExcel, 'Excel5');
        // Sendingheaderstoforcetheusertodownloadthefile
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename="Products_' . date('dMy') . '.xls"');
        header('Cache-Control:max-age=0');
        $objWriter -> save('php://output');
        }
    }

4.测试

加入数据库有表名为products,此时可以访问http://www.yoursite.com/table_export/index/products导出Excel文件了。

上一篇:PHP使用Alexa API获取网站的Alexa排名例子
下一篇:Codeigniter生成Excel文档的简单方法
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。