CodeIgniter 导出 CSV 和 Excel 文件

导出 CSV 文件:
Code:
function _exportCsv()
{
$this->load->dbutil();
$query = $this->db->get('your_table');
return $this->dbutil->csv_from_result($query);
}

function export()
{
$this->load->helper('download');
$csv = $this->_exportCsv();
$name = 'name_'.date('Y-m-d').'.csv';
force_download($name, $csv);
}

导出 Excel 文件:
使用一个 CodeIgniter 的插件 Excel Plugin
./system/plugins/to_excel_pi.php
Excel Plugin Code:
function to_excel($query, $filename='exceloutput')
{
$headers = ''; // just creating the var for field headers to append to below
$data = ''; // just creating the var for field data to append to below

$obj =& get_instance();

$fields = $query->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 "$headers\n$data";
}
}

/* End of file to_excel_pi.php */
/* Location: ./system/plugins/to_excel_pi.php */

实现 Code:
function exportexcel()
{
$this->load->plugin('to_excel');
$query = $this->db->query("select * from your_table");
to_excel($query, 'working_time_'.date('Y-m-d'));
}

没有评论:

发表评论