Import Data From Excel & CSV to mysql Using Codeigniter

Import Data From Excel & CSV to mysql Using Codeigniter

In this codeigniter excel,csv import tutorial, we will would love to share with you how to import data as Excel or CSV file format in CodeIgniter. Excel and csv is the best technique to Import data in a file and you can easily import data to Excel or CSV using Codeigniter excel library.

Codeigniter Import Excel,CSV File

  • Download Codeigniter Latest
  • Basic Configurations
  • Download phpExcel Library
  • Create Library
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create model
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';

Download phpExcel Library

Download this excel library here : click here

Next, we need to download phpExcel library from this link, and extract into application/third_party folder. After extract this library move to PHPExcel folder like application/third_party/PHPExcel and also move PHPExcel.php file to application/third_party/PHPExcel.php.

Create Library

Now we need to create Excel.php file into application/library, So go to application/library and create one file name Excel.php and put the below code here.

if (!defined('BASEPATH')) exit('No direct script access allowed');  
require_once APPPATH."/third_party/PHPExcel.php";
class Excel extends PHPExcel {
    public function __construct() {

Create Database With Table

In this step, we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo . After successfully create a database, you can use the below sql query for creating a table in your database.

    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    first_name varchar(100) NOT NULL COMMENT 'First Name',
    last_name varchar(100) NOT NULL COMMENT 'Last Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;

Setup Database Credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE

Create Controller

Now we need to create a controller name Import.php. In this controller we will create some method/function. We will build some of the methods like :

  • Index() – This is used to showing users list
  • importFile() – This function is used to import excel or csv sheet

defined('BASEPATH') OR exit('No direct script access allowed');

class Import extends CI_Controller {
	// construct
    public function __construct() {
		// load model
        $this->load->model('Import_model', 'import');

    public function index() {

    public function importFile(){
      if ($this->input->post('submit')) {
                $path = 'uploads/';
                require_once APPPATH . "/third_party/PHPExcel.php";
                $config['upload_path'] = $path;
                $config['allowed_types'] = 'xlsx|xls|csv';
                $config['remove_spaces'] = TRUE;
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('uploadFile')) {
                    $error = array('error' => $this->upload->display_errors());
                } else {
                    $data = array('upload_data' => $this->upload->data());
                  if (!empty($data['upload_data']['file_name'])) {
                    $import_xls_file = $data['upload_data']['file_name'];
                } else {
                    $import_xls_file = 0;
                $inputFileName = $path . $import_xls_file;
                try {
                    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                    $objPHPExcel = $objReader->load($inputFileName);
                    $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                    $flag = true;
                    foreach ($allDataInSheet as $value) {
                        $flag =false;
                      $inserdata[$i]['first_name'] = $value['A'];
                      $inserdata[$i]['last_name'] = $value['B'];
                      $inserdata[$i]['email'] = $value['C'];
                      $inserdata[$i]['contact_no'] = $value['D'];
                    $result = $this->import->insert($inserdata);   
                      echo "Imported successfully";
                      echo "ERROR !";
              } catch (Exception $e) {
                   die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                            . '": ' .$e->getMessage());
                  echo $error['error'];

Create model

Now go to application/models folder and create a one model name Export_model.php . After create this model put the below query in to model.

defined('BASEPATH') OR exit('No direct script access allowed');

    class Import_model extends CI_Model {

        public function __construct()
        public function insert($data) {
            $res = $this->db->insert_batch('import',$data);
                return TRUE;
                return FALSE;

Create Views

Now we need to create import.php, go to application/views/ folder and create Import.php file. Here put the below html code for showing list of product.

<!DOCTYPE html>
  <title>Codeigniter Import Example</title>
 <link rel="stylesheet" href="" />
<script src=""></script>
<form action="<?php echo base_url();?>import/importFile" method="post" enctype="multipart/form-data">
    Upload excel file : 
    <input type="file" name="uploadFile" value="" /><br><br>
    <input type="submit" name="submit" value="Upload" />

Start Development server

For start development server, Go to the browser and hit below the url.



In this codeigniter excel csv import tutorial, we have successfully import csv or excel file using phpExcel library

You may like

  1. Export Data to Excel/CSV in Codeigniter Using PHPExcel
  2. Adding Multiple Markers To Google Maps From Database PHP Codeigniter
  3. Integrate Razorpay with PHP Codeigniter
  4. Implement Google Column Chart With PHP Codeigniter
  5. Google Bar & Line Charts Days Wise MySQL PHP Codeigniter
  6. Codeigniter Pagination Library Example
  7. Morris Area & Line Chart With Codeigniter Example

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Codeigniter, Vue JS, Angular JS, React Js, WordPress and Bootstrap from a starting stage.

Leave a Reply

Your email address will not be published. Required fields are marked *