|
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技术:Codeigniter+PHPExcel实现导出数据到Excel文件,转载需保留来源!
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。