Senin, 01 Agustus 2011

PHP Codeigniter - Export data dari database ke excel

export data from database to excel.

Pada kali ini saya juga akan sharing tentang export data dari database ke excel, dengan menggunakan library excel_reader2 yang bisa di download di http://code.google.com/p/php-excel-reader/downloads/list atau mirror

Sebelumnya, sharing ini adalah kelanjutan atau bisa dibilang masih berhubungan dengan sharing yang sebelumnya, yaitu sharing tentang penggunaan CI + jQuery 1.3.2  + Colorbox + Flexigrid. Jadi alangkah baikknya jika baca sharing yang sebelumnya, karena file yang ada di sharing tersebut dipakai pada sharing kali ini.. hehe

Langsung saja, pada sharing tentang export data ke excel ini cukup mudah dan simple (hehe bukannya sombong loh... XD),
jika excel_reader2 sudah di download taruh file excel_readernya dalam library untuk CI Versi 2 ada di folder CI_Root/application/libraries.
Selanjutnya edit file user.php dan buat fungsi export dan set_header seperti di bawah ini
function export(){
  $header = $this->set_header();
  $data = array($header);
    
  $filename  = 'Laporan_User';
  $loop = 0;
  foreach($this->user_model->getUser()->result() as $row){   
   $content[$loop] = array($row->USERNAME, $row->NAME, $row->EMAIL, $row->ADDRESS);
   array_push($data, $content[$loop]);
   $loop++;    
  }
  $this->load->helper('to_excel');
  array_to_excel($data, $filename); 
 }
  
 function set_header(){
  return array('Username','Nama','Email','Alamat');
 }

Setelah itu, edit pula file user_view.php
tambahkan button untuk export excel seperti contoh di bawah ini.
{name: 'Export', bclass: 'add', onpress : action}, // bclass : 'add' hanya untuk tampilan icon yg akan ditampilkan
{separator: true}

Setelah itu, tambahkan kondisi pada fungsi action pada user_view.php
if (com == 'Export') {
 if(confirm('Export to Excel file ?')) {
  export_excel();
 }
}

Tambahkan pula fungsi export_excel pada user_view.php
function export_excel() {
 window.open("<?php echo $url_form?>/export/","export_window");
}

Dan yang terakhir, buat file dengan nama to_excel_helper.php dan taruh dalam folder helper di CI.
if (!defined('BASEPATH')) exit('No direct script access allowed'); 

function to_excel($query, $filename='xlsoutput') 
{ 
     $headers = ''; // variable untuk menampung header 
     $data = ''; // variable untuk menampung data 

     //$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"; 
     } 
} 

function array_to_excel($array, $filename='xlsoutput') 
{ 
     $headers = ''; // variable untuk menampung header 
     $data = ''; // variable untuk menampung data 

     //$obj =& get_instance(); 

     //$fields = $query->field_data(); 
     if (sizeof($array) == 0) { 
          echo 'The table appears to have no data.'; 
     } else { 
          foreach ($array 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/ms-excel'); 
        header("Content-Disposition: attachment; filename=$filename.xls"); 
        echo $data; 
     } 
}
Nah, lumayan mudah kan untuk export dari database ke file excel...

Sekian sharing untuk export ke file excel.
Semoga bisa bermanfaat... ^_^


Keyword : PHP CodeIgniter, Export to excel, excel reader

Untuk menghargai HKI(Hak Kekayaan Intelektual), sumber referensi yang saya pakai dan saya pelajari akan ditampilkan.
Referensi    : http://code.google.com/p/php-excel-reader/
Author       : Moch. Zawaruddin Abdullah, www.zawaruddin.blogspot.com

11 komentar:

  1. om, mau tanya, kalau nambahin text didalam excel gimana fungsinya? thank's

    BalasHapus
    Balasan
    1. maaf baru balas... bisa tambahin di controllernya, masukin teks nya pada fungsion export, variabel $data

      Hapus
    2. mas model_user.php nya gimana?

      Hapus
  2. untuk CI 1.7 bisa di buat tutorialnya mas ?

    BalasHapus
    Balasan
    1. itu juga bisa buat CI 1.7, bisa dilihat d controller sama helpernya...

      Hapus
  3. Mkasih om tutorial'a
    it's work

    BalasHapus
  4. code ini bisa gan tapi ko selesai download buka filenya ada peringatan dari excelnya ya seperti ini ; "The file format and extension of 'nama_fileku.xls' don'tmatch. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway? Yes No Help"

    BalasHapus
  5. mas kalo CI 3.0.0 bisa juga kan ,,, tp file user.phpitu yang di mana nya? maaf , newbie

    BalasHapus
  6. mas tata letak file nya seperti apa ,,, misalnya file user.php di bagian mana , user_view.php di bagian mana?
    terima kasih atas tutorialnya....

    BalasHapus
    Balasan
    1. user.php itu controller jd d taruh di folder controllers,
      klo user_view.php di taruh di folder views...

      Hapus