Import csv file to database in codeigniter

Codegniter provides a lot of libraries such as session, Spreadsheet_Excel_Reader, zip, paginations etc. Here i used Spreadsheet_Excel_Reader for reading excel sheet file as csv file. first we needs to be include this library in controller. We must needs the copy of in the application/libraries folder. So, it is worked, otherwise it doesn't working. After that we create any object of that file, and use that object to reading csv file.

First, we make view file as upload code write in the view section. In that view form form with action to controller function name with form mutipart. We can use any types of file uploader. The importance part is to validation of file type, if it is csv or not. If it is csv then and then allowed, otherwise it gives an alert message like file types must be csv, no other files must be allowed.

Second, to make model section to store data which is arrieved from control file. So, must be include the database library. Then make function for database insert operation in the specied table. The details include column name with values must be insert into table. There are must same name as in table name, other wise get message like No column found.

function insert_detail($detail){
		$this->db->insert("users", $detail);
		return $this->db->insert_id(); 

The last and importance part is controller section, first we must include the Spreadsheet_Excel_Reader library. Then create object of Spreadsheet_Excel_Reader class with argument as temp file name.There are also needs to make dump with two argument True. The csv file have content like comma seprated. Thus we must to split data from cromma and also calculate number of data in one string.

Based on this number we get how much column to be included. We get all column data in the one array and call the insert model funcation and pass argument as array. Thus process is until all rows are included.

function import_file(){
            if(isset($_FILES['import'])) {
                //error_reporting(E_ALL & ~E_NOTICE & ~DEPRECATED);
                $this->exel = new Spreadsheet_Excel_Reader($_FILES['import']['tmp_name']);
                $str = $this->exel->dump(true,true);	
                $str = explode(',',$str);
	        $count_array = count($str);
                for($i=2;$i<$count_array;$i++) {
                $user_data = array();
                $user_data['EmployeeID'] = stripslashes($this->exel->val($i,'A'));
                $user_data['EmployeeName'] = stripslashes($this->exel->val($i,'B'));
                $this->message_stack->add_message('message','Import data Successfully ');

At last, we import csv file and get data to be saved in the database. we can retrived from database and diplayed in the table formate.


Let's Think together, Say Something !