Following sharing code with step wise: 1) Create database: CREATE TABLE IF NOT EXISTS `student` (   `id` int(11) NOT NULL AUTO_INCREMEN...

Export data to excel sheet using codeigniter

Following sharing code with step wise:

1) Create database:
CREATE TABLE IF NOT EXISTS `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `emai_id` varchar(50) NOT NULL,
  `phone_number` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

2)Insert data into table:
INSERT INTO `student`(`id`, `name`, `emai_id`, `phone_number`) VALUES
(1, 'ABC', 'ABC.ABC@gmail.com', '9900000000'),
(2, 'DEF', 'DEF.DEF@gmail.com', '8700000000'),
(3, 'GHI', 'GHI.GHI@gmail.com', '7700000000'),
(4, 'JKL', 'JKL.JKL@gmail.com', '7800000000');

3) Download PHPReport library and put it in  libraries directory in project.

4)now we need to create empty excel sheet as per following :

5) Create controller and model

controller - excel.php : 

<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');    
class Excel extends CI_Controller {
      function __Construct(){
        parent::__Construct();
        $this->load->model('excel_model'); 
        $this->load->helper(array('form', 'url'));
        $this->load->helper('download');
        $this->load->library('PHPReport');             
        }
    public function index(){
      // get data from databse
      $data = $this->excel_model->getdata(); 
      $template = 'Myexcel.xlsx';
      //set path to directory with template files
      $templateDir = __DIR__ . "/../controllers/"; 
      //set config for report
      $config = array(
        'template' => $template,
        'templateDir' => $templateDir
      ); 
      //load template
      $R = new PHPReport($config); 
      $R->load(array(
              'id' => 'student',
              'repeat' => TRUE,
              'data' => $data  ));       
      // define output directoy 
      $output_file_dir = "/tmp/";   
      $output_file_excel = $output_file_dir  . "Myexcel.xlsx";
      //download excel sheet with data in /tmp folder
      $result = $R->render('excel', $output_file_excel);
     }

Model- excel_model.php

<?php 
class Excel_model extends CI_Model{
function __construct(){
parent::__Construct(); 
$this->db = $this->load->database('default', TRUE,TRUE);
}
  function getdata(){
     $this->db->select('*');
     $query = $this->db->get('student');
     return $query->result_array();
  } 
}

Output: 




Fruxinfo Pt.Ltd..

0 coment�rios: