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),代码如下:
db->get($table_name); 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); // 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'); // sending headers to force the user to download the file 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'); }}?>
方法二,代码如下:
excel plugin the following plugin will generate a tab-delimited file, and feed it to the client as an excel file. $this->load->plugin('to_excel'); $this->db->use_table('tablename'); $this->db->select('field1', 'field2'); // run joins, order by, where, or anything else here $query = $this->db->get(); to_excel($query, ['filename']); // filename is optional, without it, the plugin will default to 'exceloutput' so you could run: to_excel($query, 'myfile'); // outputs myfile.xls to_excel($query); // outputs exceloutput.xls // you could also use a model here to_excel($this->model_name->functioncall()); /system/plugins/to_excel_pi.php
field_data(); if ($query->num_rows() == 0) { echo 'the table appears to have no data.
'; } else { foreach ($fields as $field) { $headers.= $field->name . t; } foreach ($query->result() as $row) { $line = ''; foreach ($row as $value) { if ((!isset($value)) or ($value == )) { $value = t; } else { $value = str_replace('', '', $value); $value = '' . $value . '' . t; } $line.= $value; } $data.= trim($line) . n; } $data = str_replace(r, , $data); header(content-type: application/x-msdownload); header(content-disposition: attachment; filename=$filename.xls); echo $headersn$data; }}?>
本文地址:
转载随意,但请附上文章地址:-)