Import file excel xls ke database dengan codeigniter

Skip to content

In this tutorial, we will would love to share with you how to import excel file data in MySql database using PHP CodeIgniter.

Import file excel xls ke database dengan codeigniter

Step 1: Create one table like `EMPLOYEE_MASTER_DATA`

CREATE TABLE `EMPLOYEE_MASTER_DATA` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `EMP_NO` varchar(50) DEFAULT NULL,
  `EMP_NAME` varchar(255) DEFAULT NULL,
  `ADDRESS` text DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2: Create one file and write below simple HTML code

<form method="post" enctype="multipart/form-data" action="https://app.shinerweb.com/index.php/import_excel/save_entry">
<input type="file" id="excel_file" name="excel_file">
  <input type="submit" value="Upload">
</form>
<br>
<a download href="<?php echo base_url() ?>/uploads/template/Data Upload Template.xlsx">Download template file</a>

Step 3: Write below code in your controller file if you are using simple PHP then skip this code.

function save_entry()
    {
        $this->load->model('import_excel_model');
		$this->import_excel_model->save_entry();
    }

Step 4: You need to create one folder like “uploads” into your project folder.

Import file excel xls ke database dengan codeigniter

Step 5: Finally you need to write logic to store excel data into the database.

function save_entry()
	{	
		include_once('excel_reader2.php');
		include_once('SpreadsheetReader.php');
		$mimes = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.oasis.opendocument.spreadsheet','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
		
		//echo $_FILES["excel_file"]["type"];
		//exit;
		
		if(in_array($_FILES["excel_file"]["type"],$mimes)){
			$uploadFilePath = 'uploads/'.basename($_FILES['excel_file']['name']);
			move_uploaded_file($_FILES['excel_file']['tmp_name'], $uploadFilePath);
			$Reader = new SpreadsheetReader($uploadFilePath);
			$totalSheet = count($Reader->sheets());

			/* For Loop for all sheets */
			for($i=0;$i<$totalSheet;$i++){
			  $Reader->ChangeSheet($i);
			  $row_count=0;
			  foreach ($Reader as $Row)
			  {
				if($row_count!=0)
				{
					$EMP_NO = isset($Row[0]) ? $Row[0] : '';
					$EMP_NAME = isset($Row[1]) ? $Row[1] : '';
					$ADDRESS = isset($Row[2]) ? $Row[2] : '';
					
					$data = array(
							'EMP_NO'      => 	$EMP_NO,
							'EMP_NAME'      => 	$EMP_NAME,
							'ADDRESS'      => 	$ADDRESS
							);
					$this->db->insert('EMPLOYEE_MASTER_DATA', $data);
				}
				$row_count++;
				
			  }
			}
			$row_count=$row_count-1;
			
			echo "<script>alert('".$row_count." Record(s) has been inserted! Thank you.') </script>";  	
			echo "<script language=\"javascript\">window.open('https://app.shinerweb.com/index.php/import_excel/', '_self');  </script>";
			
		}
		else
		{
			echo "<script>alert('Please select valid excel file!.') </script>";  	
			echo "<script language=\"javascript\">window.open('https://app.shinerweb.com/index.php/import_excel/', '_self');  </script>";
		}
		
	}

In above code you must have to include below library into your code or your project folder.

Import file excel xls ke database dengan codeigniter

EXCEL IMPORT

Home » Codeigniter , PHP » CARA IMPORT DATA DARI EXCEL KE DATABASE MENGGUNAKAN CODEIGNITER

Menginput satu persatu data kedalam database merupakan hal yang melelahkan apalagi ketika data yang di input berjumlah ratusan atau bahkan ribuan. Untuk mengatasi hal ini bisa menggunakan file excel, dimana terlebih dahulu data di buat dalam bentuk excel kemudian di upload ke WEB yang nantinya akan otomatis di masukkan kedalam database.

Pada postingan kali ini menggunakan framework Codeigniter dan menggunakan library PhpSpreadsheet. Jadi sebelum memulai bergelut dengan pembuatan, silahkan download terlebih dahulu library PhpSpreadsheet dengan menggunakan bantuan composer. Ketikkan perintah dibawah untuk mendownlaod


composer require phpoffice/phpspreadsheet

Berikut adalah contoh penggunaan Import Data Dari Excel Ke Database Menggunakan Codeigniter, dimana pada contoh ini menggunakan struktur database seperti pada gamabar.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

class Contoller extends CI_Controller {

public function aksi()
{
$file_mimes = array('application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

if(isset($_FILES['file']['name']) && in_array($_FILES['file']['type'], $file_mimes)) {

$arr_file = explode('.', $_FILES['file']['name']);
$extension = end($arr_file);

if('csv' == $extension) {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
} else {
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}

$spreadsheet = $reader->load($_FILES['file']['tmp_name']);

$sheetData = $spreadsheet->getActiveSheet()->toArray();

for($i = 1;$i < count($sheetData);$i++)
{
$nama = $sheetData[$i]['0'];
$username = $sheetData[$i]['1'];
$password = $sheetData[$i]['2'];

$nra_fix = str_replace(' ', '', $nra);

$ar = array(
'nama' => $nama,
'username' => $username,
'password' => $password
);

$a = $this->Modelku->get('user', "username='$username'")->result_array();
if (count($a)==0) {
$this->Modelku->insert('user', $ar);
}
}

}
}
}

Perlu diperhatikan kode di atas menggunakan sebuah model dengan nama "Modelku", jadi silahkan buat model dengan nama yang sama terlebih dahulu kemudian tambahkan fungsi berikut.


function insert($table, $data)
{
	$this->db->insert($table,$data);
	return $this->db->insert_id();
}
function get($tabel, $where)
{
	$this->db->select("*");
	$this->db->from($tabel);
	$this->db->where($where);
	return $this->db->get();

}