Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 CI中使用PHPExcel导出数据到Excel

CI中使用PHPExcel导出数据到Excel

发布时间:2015-01-19   编辑:www.jquerycn.cn
CI中使用PHPExcel导出数据到Excel

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
class Table_export extends CI_Controller {

function __construct()
{
parent::__construct();

// Here you should add some sort of user validation
// to prevent strangers from pulling your table data
}

function index($table_name)
{
$this->load->database();
$query = $this->db->query("select * from `$table_name` WHERE del= 1");
// $query = mb_convert_encoding("gb2312", "UTF-8", $query);
if(!$query)
return false;

// Starting the PHPExcel library
$this->load->library('PHPExcel');
$this->load->library('PHPExcel/IOFactory');

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");

$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', iconv('gbk', 'utf-8', '中文Hello'))
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello');
// Field names in the first row
$fields = $query->list_fields();
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
$col++;
}

// Fetching the table data
$row = 2;
foreach($query->result() as $data)
{
$col = 0;
foreach ($fields as $field)
{
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
$col++;
}

$row++;
}

$objPHPExcel->setActiveSheetIndex(0);

$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

//发送标题强制用户下载文件
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');
}
}
?>

加入数据库有表名为products,然后访问http://www.yourwebsite.com/table_export/index/products 就可以导出excel文件了。

您可能感兴趣的文章:
phpexcel导出数据的实例代码
phpexcel导入excel到数据库的代码
PHP导出EXCEL的简单范例 使用phpexcel类库导出excel
CI中使用PHPExcel导出数据到Excel
PHPExcel读取excel文件的例子
PHP导出excel php使用phpexcel导出excel文件
PHPExcel实例代码 phpexcel类库示例
解决php下载excel无法打开的问题
php导入excel php使用phpexcel导入excel文件
php语言怎么做表格

关键词: PHPExcel   
[关闭]