当前位置:首页 > PHP教程 > PHP常见问题

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

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

1.准备工作

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

2.安装phpexcel到codeigniter

1)解压压缩包里的classes文件夹中的内容到applicationlibraries目录下,目录结构如下:
--applicationlibrariesphpexcel.php
--applicationlibrariesphpexcel(文件夹)
2)修改applicationlibrariesphpexceliofactory.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文件了。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!