Untuk meng-import excel, pastinya menggunakan upload excel form. Contoh sistem upload excel yang saya buat ini masih sederhana. Data akan diupdate jika ada yang sama. Jika tidak, data akan di insert (dianggap sebagai data baru). Sebelumnya lagi-lagi ngingetin agar konfigurasi code igniter di awal seperti database.php, config.php harus sudah benar ^_^
1. Buat file chapter.php di application/views/. Copy paste script berikut diantara tag <body></body>
<?php echo form_open_multipart('chapter') . "\n"; ?>
<table>
<tr>
td><input type="file" id="file_upload" name="userfile" size="20" /></td>
</tr>
<tr>
<td> </td>
<td valign="top" >
<?php echo form_submit('submit', 'Upload'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
<?php
if ($this->session->flashdata('msg_excel')){
?>
<div class="msg"><?php echo $this->session->flashdata('msg_excel'); ?></div>
<?php } ?>
<tr>
td><input type="file" id="file_upload" name="userfile" size="20" /></td>
</tr>
<tr>
<td> </td>
<td valign="top" >
<?php echo form_submit('submit', 'Upload'); ?></td>
</tr>
</table>
<?php echo form_close(); ?>
<?php
if ($this->session->flashdata('msg_excel')){
?>
<div class="msg"><?php echo $this->session->flashdata('msg_excel'); ?></div>
<?php } ?>
2. Buat file chapter.php di application/controllers/
<?php
class Chapter extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Querypage');
$this->load->helper(array('form', 'url', 'inflector'));
$this->load->library('form_validation');
}
public function index()
{
if ($this->input->post('submit'))
{
class Chapter extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Querypage');
$this->load->helper(array('form', 'url', 'inflector'));
$this->load->library('form_validation');
}
public function index()
{
if ($this->input->post('submit'))
{
$this->do_upload();
// $this->load->view('chapter', $data);
}
else
{
$this->load->view('chapter', $data);
}
}
// $this->load->view('chapter', $data);
}
else
{
$this->load->view('chapter', $data);
}
}
function do_upload()
{
$config['upload_path'] = './temp_upload/';
$config['allowed_types'] = 'xls';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$data = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_excel', 'Insert failed. Please check your file, only .xls file allowed.');
}
else
{
$data = array('error' => false);
$upload_data = $this->upload->data();
$this->load->library('excel_reader');
$this->excel_reader->setOutputEncoding('CP1251');
$file = $upload_data['full_path'];
$this->excel_reader->read($file);
error_reporting(E_ALL ^ E_NOTICE);
// Sheet 1
$data = $this->excel_reader->sheets[0] ;
$dataexcel = Array();
for ($i = 1; $i <= $data['numRows']; $i++) {
if($data['cells'][$i][1] == '') break;
$dataexcel[$i-1]['chapternumber'] = $data['cells'][$i][1];
$dataexcel[$i-1]['title'] = $data['cells'][$i][2];
$dataexcel[$i-1]['text1'] = $data['cells'][$i][3];
$dataexcel[$i-1]['text2'] = $data['cells'][$i][4];
}
//cek data
$check= $this->Querypage->search_chapter($dataexcel);
if (count($check) > 0)
{
$this->Querypage->update_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'update data success');
}else{
$this->Querypage->insert_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'inserting data success');
}
}
redirect('chapter');
}
}
?>
{
$config['upload_path'] = './temp_upload/';
$config['allowed_types'] = 'xls';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$data = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_excel', 'Insert failed. Please check your file, only .xls file allowed.');
}
else
{
$data = array('error' => false);
$upload_data = $this->upload->data();
$this->load->library('excel_reader');
$this->excel_reader->setOutputEncoding('CP1251');
$file = $upload_data['full_path'];
$this->excel_reader->read($file);
error_reporting(E_ALL ^ E_NOTICE);
// Sheet 1
$data = $this->excel_reader->sheets[0] ;
$dataexcel = Array();
for ($i = 1; $i <= $data['numRows']; $i++) {
if($data['cells'][$i][1] == '') break;
$dataexcel[$i-1]['chapternumber'] = $data['cells'][$i][1];
$dataexcel[$i-1]['title'] = $data['cells'][$i][2];
$dataexcel[$i-1]['text1'] = $data['cells'][$i][3];
$dataexcel[$i-1]['text2'] = $data['cells'][$i][4];
}
//cek data
$check= $this->Querypage->search_chapter($dataexcel);
if (count($check) > 0)
{
$this->Querypage->update_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'update data success');
}else{
$this->Querypage->insert_chapter($dataexcel);
// set pesan
$this->session->set_flashdata('msg_excel', 'inserting data success');
}
}
redirect('chapter');
}
}
?>
3. Buat file querypage.php di application/models/
<?php
class Querypage extends CI_Model {
function __construct()
{
parent::__construct();
}
function insert_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
'title'=>$dataarray[$i]['title'],
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateinserted' => date('Y-m-d H:i:s', now())
);
$this->db->insert('content', $data);
}
}
function update_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
class Querypage extends CI_Model {
function __construct()
{
parent::__construct();
}
function insert_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
'title'=>$dataarray[$i]['title'],
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateinserted' => date('Y-m-d H:i:s', now())
);
$this->db->insert('content', $data);
}
}
function update_chapter($dataarray)
{
for($i=1;$i<count($dataarray);$i++){
$data = array(
'chapternumber'=>$dataarray[$i]['chapternumber'],
'title'=>$dataarray[$i]['title'],
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateupdated' => date('Y-m-d H:i:s', now())
);
$param = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
$this->db->where($param);
return $this->db->update('content',$data);
}
}
function search_chapter($dataarray){
for($i=1;$i<count($dataarray);$i++){
$search = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
}
$data = array();
$this->db->where($search);
$this->db->limit(1);
$Q = $this->db->get('content');
if($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
?>
'text1'=>$dataarray[$i]['text1'],
'text2'=>$dataarray[$i]['text2'],
'dateupdated' => date('Y-m-d H:i:s', now())
);
$param = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
$this->db->where($param);
return $this->db->update('content',$data);
}
}
function search_chapter($dataarray){
for($i=1;$i<count($dataarray);$i++){
$search = array(
'chapternumber'=>$dataarray[$i]['chapternumber']
);
}
$data = array();
$this->db->where($search);
$this->db->limit(1);
$Q = $this->db->get('content');
if($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
?>
keterangan: data akan diupdate jika ada chapternumber yang sama dalam file excel.
4. Download excel reader disini. Ekstrak, kemudian copy paste ke folder application/libraries/
5. Buat folder temp_upload sejajar dengan application, system, css (jika ada)
6. Jangan lupa siapin database-nya
4. Download excel reader disini. Ekstrak, kemudian copy paste ke folder application/libraries/
5. Buat folder temp_upload sejajar dengan application, system, css (jika ada)
6. Jangan lupa siapin database-nya
CREATE TABLE `content` (
`id` int(11) NOT NULL auto_increment,
`id` int(11) NOT NULL auto_increment,
`ChapterNumber` int(3) NOT NULL default '0',
`Title` varchar(50) default NULL,
`Title` varchar(50) default NULL,
`Text1` text,
`Text2` text,
`Text2` text,
`DateInserted` datetime default NULL,
`DateUpdated` datetime default NULL,
PRIMARY KEY (`Code`,`ChapterNumber`),
UNIQUE KEY `ID` (`id`)
)
`DateUpdated` datetime default NULL,
PRIMARY KEY (`Code`,`ChapterNumber`),
UNIQUE KEY `ID` (`id`)
)
7. Done.
8. Jalankan dibrowser http://localhost/namaweb/index.php/chapter
Selamat mencoba :)
8. Jalankan dibrowser http://localhost/namaweb/index.php/chapter
Selamat mencoba :)
Mbak, ko saya error nya "Insert failed. Please check your file, only .xls file allowed."
BalasHapuspadahal saya udh mengupload file yg ekstensi nya xls,. saya pakai ci 1.7.3 da class extendsnya udh saya ganti jg
mohon bantuannya
message error tsb sebetulnya untuk memberikan pesan bahwa file tidak ter-upload. penyebabnya bisa beberapa hal:
BalasHapus1. Coba cek file. hanya file ber-ekstensi .xls yg diijinkan
2. Cek codingan :) . excel reader-nya sudah ada betul/tidak atau path upload sudah tersedia/belum
3. Saat upload, sebaiknya file tidak dlm kondisi dibuka. (untuk IE)
semoga membantu :)
Edit pada file mimes di folder config,cek type file dengan $_FILES['upload']['type']. Jika hasil type belum ada di mimes, dapat ditambahkan pada bagian xls. Semoga bermanfaat
BalasHapusKomentar ini telah dihapus oleh pengarang.
BalasHapusmbak,maaf nih..saya masih newbie.saya ada error
BalasHapusSeverity: Notice
Message: Undefined variable: data
Filename: controllers/chapter.php
Line Number: 19
dan juga ketika upload "Insert failed. Please check your file, only .xls file allowed."
bisa minta tolong buat mbetulin error ini?
bisa minta sourcecode nya??? saya mengalami error
BalasHapusSeverity: Notice
Message: Undefined variable: data
Filename: controllers/chapter.php
Line Number: 19
Hapus aja di baris 19 $data nya
BalasHapus$this->load->view('chapter', $data);
karena $data belum di deklarasikan sebelumnya.
thanks bgt nih..
BalasHapustutorialnya berjalan normal di tempat saya :)
Komentar ini telah dihapus oleh pengarang.
BalasHapushi tolong bantuannya
BalasHapusada error seperti ini
A PHP Error was encountered
Severity: Notice
Message: Undefined property: CI_Loader::$session
Filename: views/chapter.php
Line Number: 14
di line 14
codenya ini
if ($this->session->flashdata('msg_excel')){
teh, saya lg nyoba upload file aja, tp kenapa ga ada terus yah file yang saya maksudkan untuk upload?
BalasHapusmbak ini hanya bisa import file xls aja ya tidak bisa file xlsx yang baru?
BalasHapus
BalasHapusA PHP Error was encountered
Severity: Notice
Message: Undefined variable: formatstr
Filename: libraries/excel_reader.php
Line Number: 635
Saya ada field tanggal, di excel sudah saya buat tipe Date. Apakah ada masalah y Om ?
Sudah g ada masalah,,tapi kenapa perulangannya cuma sekali pak ? Data saya 1901 record, tapi looping cm sekali.mohon dibantu
BalasHapus$param = array(
BalasHapus'chapternumber'=>$dataarray[$i]['chapternumber']
);
$this->db->where($param);
return $this->db->update('content',$data);
}
itu gunanya untuk apa ya?