Cara menggunakan excel import codeigniter 3

PhpSpreadsheet is a PHP library for reading and writing spreadsheet files. Import Excel and CSV into MySQL help to save the user time and avoid repetitive work.

Software requirements

PHP version 7.2 or newer to develop using PhpSpreadsheet. Other requirements, such as PHP extensions, are enforced by the composer.

Installation
  1. Download and install CodeIgniter.
  2. Use Composer to install PhpSpreadsheet into your project: composer require phpoffice/phpspreadsheet
  3. Open application/config/config.php file and set your vendor directory path. $config['composer_autoload'] = 'vendor/autoload.php';
  4. Use phpspreadsheet the library inside your controller.
Create MySQL Database and Table

The following SQL query creates a


$route['user/import'] = 'Upload/import';

?>
0 table in the MySQL database.

CREATE TABLE `client_info` (
`id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`country_code` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
`mobile` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`city` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`ip_address` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`status` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Create Routes

Open


$route['user/import'] = 'Upload/import';

?>
1 file and add the following lines.


$route['user/import'] = 'Upload/import';

?>
Create Model

Create a model file named User_model.php inside the


$route['user/import'] = 'Upload/import';

?>
2 folder.

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

class User_model extends CI_Model {

public function __construct() {
parent::__construct();
$this->table = 'user_info';
}

public function add($data) {
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}

public function update($where, $data) {
return $this->db->update($this->table, $data, $where);
}

public function delete($where) {
return $this->db->delete($this->table, $where);
}

public function get($where = 0) {
if($where)
$this->db->where($where);
$query = $this->db->get($this->table);
return $query->row();
}

public function get_all($where = 0, $order_by_column = 0, $order_by = 0) {
if($where)
$this->db->where($where);
if($order_by_column and $order_by)
$this->db->order_by($order_by_column, $order_by);
$query = $this->db->get($this->table);
return $query->result();
}

public function get_num_rows($where = 0) {
if($where)
$this->db->where($where);
$query = $this->db->get($this->table);
return $query->num_rows();
}

public function add_batch($data) {
return $this->db->insert_batch($this->table, $data);
}

}
Create Controller and load class

Create a controller named Upload.php and use the PHPSpreadsheet library inside the controller. See the following code for the controller.

defined('BASEPATH') OR exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata');
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Upload extends CI_Controller {

public function __construct() {
parent::__construct();
// Load Model
$this->load->model('User_model', 'user');
$this->ip_address = $_SERVER['REMOTE_ADDR'];
$this->datetime = date("Y-m-d H:i:s");
}

public function index() {
$this->load->view("index");
}

public function display() {
$data = [];
$data ["result"] = $this->user->get_all();
$this->load->view("index");
}

public function import() {
$path = 'documents/users/';
$json = [];
$this->upload_config($path);
if (!$this->upload->do_upload('file')) {
$json = [
'error_message' => showErrorMessage($this->upload->display_errors()),
];
} else {
$file_data = $this->upload->data();
$file_name = $path.$file_data['file_name'];
$arr_file = explode('.', $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($file_name);
$sheet_data = $spreadsheet->getActiveSheet()->toArray();
$list = [];
foreach($sheet_data as $key => $val) {
if($key != 0) {
$result = $this->user->get(["country_code" => $val[2], "mobile" => $val[3]]);
if($result) {
} else {
$list [] = [
'name' => $val[0],
'country_code' => $val[1],
'mobile' => $val[2],
'email' => $val[3],
'city' => $val[4],
'ip_address' => $this->ip_address,
'created_at' => $this->datetime,
'status' => "1",
];
}
}
}
if(file_exists($file_name))
unlink($file_name);
if(count($list) > 0) {
$result = $this->user->add_batch($list);
if($result) {
$json = [
'success_message' => showSuccessMessage("All Entries are imported successfully."),
];
} else {
$json = [
'error_message' => showErrorMessage("Something went wrong. Please try again.")
];
}
} else {
$json = [
'error_message' => showErrorMessage("No new record is found."),
];
}
}
echo json_encode($json);
}

public function upload_config($path) {
if (!is_dir($path))
mkdir($path, 0777, TRUE);
$config['upload_path'] = './'.$path;
$config['allowed_types'] = 'csv|CSV|xlsx|XLSX|xls|XLS';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 4096;
$this->load->library('upload', $config);
}
}
Create View

Create a view named index.php inside the


$route['user/import'] = 'Upload/import';

?>
3 directory. See the following code for the view file.




Upload













Upload excel or csv file only.















Create View

Create a view named display.php inside the


$route['user/import'] = 'Upload/import';

?>
3 directory. See the following code for the view file.