我们用最简单的方法直接用php+mysql来实现了,代码如下:
-
<?php
-
include('db/db.php');
-
$db = new db();
-
$result = mysql_query('select * from market_sig into outfile "d:product3.xls";');
-
var_dump($result);
-
?>
上面是我们的原生php结合了mysql outfile文件导出方法,这种方法有个问题就是不能实现下载功能,只在生成在服务器上.
下面方法更全面:下载PHPExcel:http://phpexcel.codeplex.com
先来看看代码,代码如下:
-
<?php
-
-
class Table_export extends CI_Controller {
-
-
function __construct()
-
{
-
parent::__construct();
-
-
-
-
}
-
-
function index($table_name)
-
{
-
$this->load->database();
-
$query = $this->db->query("select * from `$table_name` WHERE del= 1");
-
-
if(!$query)
-
return false;
-
-
-
$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');
-
-
$fields = $query->list_fields();
-
$col = 0;
-
foreach ($fields as $field)
-
{
-
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
-
$col++;
-
}
-
-
-
$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');
-
}
-
-
}
-
?>
看看配置方法吧.
1) 解压压缩包里的Classes文件夹中的内容到applicationlibraries目录下,目录结构如下:
-- applicationlibrariesPHPExcel.php
-- applicationlibrariesPHPExcel(文件夹)
2) 修改applicationlibrariesPHPExcelIOFactory.php 文件
-- 将其类名从PHPExcel_IOFactory改为IOFactory,遵从CI类命名规则.
-- 将其构造函数改为public.
还有很多方法像这种方法多喜欢用,因为phpexcel这个插件很实用,对excel表格操作方便.
(责任编辑:最模板) |