`
天梯梦
  • 浏览: 13648226 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

codeigniter 生成 excel

阅读更多

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

 

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
* Excel library for Code Igniter applications
* Author: Derek Allard, Dark Horse Consulting, www.darkhorse.to, April 2006
*/

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 '<p>The table appears to have no data.</p>';
     } 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";  
     }
}
?>
 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics