How to export to excel in codeigniter 3

Leave a Comment
Today we gonna learn how to export to excel in codeigniter 3 without using any library. Download codeigniter and i already created test database. lets check our database



We are ready with our database lets start with controller i.e. ExportExcel.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class ExportExcel extends CI_Controller {

 function __construct()
 {
  parent::__construct();
  $this->load->database();
 }
 

 public function exportExcelData($records)
 {
  $heading = false;
        if (!empty($records))
            foreach ($records as $row) {
                if (!$heading) {
                    // display field/column names as a first row
                    echo implode("\t", array_keys($row)) . "\n";
                    $heading = true;
                }
                echo implode("\t", ($row)) . "\n";
            }
 }

 public function fetchDataFromTable()
 {
  $query =$this->db->get('one_piece_characters'); // fetch Data from table
  $allData = $query->result_array();  // this will return all data into array
  $dataToExports = [];
  foreach ($allData as $data) {
   $arrangeData['Charater Name'] = $data['name'];
   $arrangeData['Charater Profile'] = $data['profile'];
   $arrangeData['Charater Desc'] = $data['description'];
   $dataToExports[] = $arrangeData;
  }
  // set header
  $filename = "dataToExport.xls";
                header("Content-Type: application/vnd.ms-excel");
                header("Content-Disposition: attachment; filename=\"$filename\"");
  $this->exportExcelData($dataToExports);
 }
}

Now hit this url http://localhost/ci_tuts/index.php/ExportExcel/fetchDataFromTable. After hitting this url you will get your excel sheets.

Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .

0 comments:

Post a Comment

Powered by Blogger.