Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
How To Import Excel and CSV File Using CodeIgniter

How To Import Excel and CSV File Using CodeIgniter

Posted on September 3, 2019December 17, 2022 By XpertPhp No Comments on How To Import Excel and CSV File Using CodeIgniter

Today, In this tutorial, we will be explaining how to import Excel and CSV File Using CodeIgniter. so let’s discuss Import Excel and CSV File.

It’s also very helpful in such as if you want to backup of data and you have data of CSV file then you can import the data into the database.

CSV extension stands for “Comma Separated Values” and contains all data in comma-separated. Normally, we have large data and need to import data into the database that time we use the following file types.

Overview

Step 1: Create a Database in table
Step 2: Connect to Database
Step 3: Download PhpExcel Library
Step 4: Create Controller
Step 5: Create a Model
Step 6: Create View File

Step 1: Create a Database in table
In this step, we have to create a table in the database, so we will create a database using the below code.

1
2
3
4
5
6
7
8
9
CREATE TABLE IF NOT EXISTS `register` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(64) NOT NULL,
  `last_name` varchar(64) NOT NULL,
  `address` text NOT NULL,
  `email` varchar(64) NOT NULL,
  `mobile` varchar(12) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

Step 2: Connect to Database
Go to the config folder and open database.php file some changes in this file like hostname, database username, database password, and database name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'enter here database name',
'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
);

Step 3: Download PhpExcel Library
First, we need to Download PhpExcel Library. then we will use that third party Library for Codeigniter excel import.
Step 4: Create Controller
In this step, we will create an Import.php file in the “application/controller” directory and paste the below code in this controller.
application/controller/Import.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
defined('BASEPATH') OR exit('No direct script access allowed');  
  
class Import extends CI_Controller {  
function __construct() {
parent::__construct();
$this->load->database();
$this->load->model('import_model');
    }
public function index(){
$query =  $this->db->query('SELECT * from register ORDER BY id desc');
$records = $query->result_array();
$data['user_data'] = $records;
$this->load->view('excel_file_upload',$data);
}
public function uploadData()
{
if ($this->input->post('submit'))
{            
$path = 'uploads/';
require_once APPPATH . "/third_party/PHPExcel.php";
$config['upload_path'] = $path;
$config['allowed_types'] = 'xlsx|xls';
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);            
if (!$this->upload->do_upload('uploadFile')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
}
if(empty($error)){
  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;
$i=0;
foreach ($allDataInSheet as $value) {
  if($flag){
$flag =false;
continue;
  }
  $inserdata[$i]['first_name'] = $value['A'];
  $inserdata[$i]['last_name'] = $value['B'];
  $inserdata[$i]['address'] = $value['C'];
  $inserdata[$i]['email'] = $value['D'];
  $inserdata[$i]['mobile'] = $value['E'];
  $i++;
}              
$result = $this->import_model->importdata($inserdata);  
if($result){
  echo "Imported successfully";
}else{
  echo "ERROR !";
}            
 
} catch (Exception $e) {
   die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' .$e->getMessage());
}
}else{
  echo $error['error'];
}        
$this->load->view('excel_file_upload');
}
}
?>
See also  How to Create Dynamic Xml Sitemap in Codeigniter

Step 5: Create a Model
In this step, we will create an Import_model.php file in the “application/models” directory and paste the below code in this model.
application/models/Import_model.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Import_model extends CI_Model {
    public function importData($data) {
        $res = $this->db->insert_batch('register',$data);
        if($res){
            return TRUE;
        }else{
            return FALSE;
        }
    }
}
?>

 

Step 6: Create View File
So finally, we will create the excel_file_upload.php file in the “application/views/” directory and make a form with google Recaptcha code in HTML.
application/views/excel_file_upload.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<!DOCTYPE html>
<html lang="en">
<head>
  <title>How To Import Excel and CSV File Using CodeIgniter - XpertPhp</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="container" style="margin-top:50px;">
  <div class="row">
<div class="col-lg-10"><h2>codeigniter excel Import</h2></div>
<div class="col-lg-1">&nbsp;</div>
<div class="col-lg-1"><button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#importModal">Import</button></div>
  </div>  
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Id</th>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Address</th>
        <th>Email</th>
        <th>Mobile</th>
      </tr>
    </thead>
    <tbody>
<?php
foreach($user_data as $row) {
?>
      <tr>
        <td><?php echo $row['id'];?></td>
        <td><?php echo $row['first_name'];?></td>
        <td><?php echo $row['last_name'];?></td>
        <td><?php echo $row['email'];?></td>
        <td><?php echo $row['phone'];?></td>
        <td><?php echo $row['created'];?></td>
      </tr>
<?php
} ?>
    </tbody>
  </table>
</div>
 
<!-- Modal -->
  <div class="modal fade" id="importModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Upload Csv file</h4>
        </div>
        <div class="modal-body">
          <form action="<?php echo base_url();?>import/uploadData" method="post" enctype="multipart/form-data">
<div class="col-lg-12">
<div class="form-group">
<input type="file" name="uploadFile" id="uploadFile" class="filestyle" data-icon="false">
</div>
</div>
<div class="col-lg-12">
<input type="submit" value="Upload file" id="upload_btn">
</div>
  </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
</body>
</html>

Codeigniter, MySql Tags:How to import Excel file into MySQL using CodeIgnitor, import csv file in codeigniter, Import excel file in codeigniter, Import excel file in codeIgnitor

Post navigation

Previous Post: How to export data in excel and CSV Files Using CodeIgniter
Next Post: how to Install Apache MySQL and PHP on Ubuntu 16.04 and 18.04

Latest Posts

  • Laravel 12 Ajax CRUD Example
  • Laravel 12 CRUD Example Tutorial
  • How to Create Dummy Data in Laravel 11
  • Laravel 11 Yajra Datatables Example
  • Laravel 11 Ajax CRUD Example
  • Laravel 11 CRUD Example Tutorial
  • Laravel 10 Ajax CRUD Example Tutorial
  • Laravel 10 CRUD Example Tutorial
  • How to disable button in React js
  • JavaScript Interview Questions and Answers

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch laravel social login learn jquery nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor wysiwyg html editor

Copyright © 2018 - 2025,

All Rights Reserved Powered by XpertPhp.com