我們用最簡單的方法直接用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();
- // 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');
- //開源代碼Vevb.com
- $objWriter->save('php://output');
- }
- }
- ?>
看看配置方法吧.
1) 解壓壓縮包里的Classes文件夾中的內容到applicationlibraries目錄下,目錄結構如下:
-- applicationlibrariesPHPExcel.php
-- applicationlibrariesPHPExcel(文件夾)
2) 修改applicationlibrariesPHPExcelIOFactory.php 文件
-- 將其類名從PHPExcel_IOFactory改為IOFactory,遵從CI類命名規則.
-- 將其構造函數改為public.
還有很多方法像這種方法多喜歡用,因為phpexcel這個插件很實用,對excel表格操作方便.
新聞熱點
疑難解答