CI Framework of CodeIgniter Implementation of Import Export Data Operation Example
- 2021-10-11 17:53:21
- OfStack
This article describes the example of CI framework (CodeIgniter) to achieve the import, export data operations. Share it for your reference, as follows:
Reference the class PHPExcel in libraies (phpexcel. php)
public function excel_put(){
// Do it first 1 Upload and save files
$path=$_FILES['file'];
$filePath = "uploads/".$path["name"];
move_uploaded_file($path["tmp_name"],$filePath);
//$data=array('B'=>'name','C'=>'pwd','D'=>'money1','E'=>'salt');
$data=array('B'=>'name','C'=>'pid');
$tablename='city2';// Table name
$this->excel_fileput($filePath,$data,$tablename);
}
private function excel_fileput($filePath,$data,$tablename){
$this->load->library("phpexcel");//ci Introduced into the framework excel Class
$PHPExcel = new PHPExcel();
$PHPReader = new PHPExcel_Reader_Excel2007();
if(!$PHPReader->canRead($filePath)){
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($filePath)){
echo 'no Excel';
return ;
}
}
// Loading excel Documents
$PHPExcel = $PHPReader->load($filePath);
// Read excel The first in the document 1 Sheets
$currentSheet = $PHPExcel->getSheet(0);
// Get the largest column number
$allColumn = $currentSheet->getHighestColumn();
// Acquire 1 How many lines are there
$allRow = $currentSheet->getHighestRow();
// From the first 2 Line starts to output because excel Table number 1 Behavior column name
for($currentRow = 2;$currentRow <= $allRow;$currentRow++){
/** From the first A Column starts to output */
//echo $allColumn;
for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){
$val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();
//print_r($val);
//die;
if($currentColumn == 'A')
{
//echo $val."\t";
}else if($currentColumn <= $allColumn){
$data1[$currentColumn]=$val;
}
}
foreach($data as $key=>$val){
$data2[$val]=$data1[$key];
}
$this->db->insert($tablename,$data2);
//print_r($data2);
//echo "</br>";
}
//echo "\n";
echo " Import succeeded ";
}
Export data:
public function excel_out(){
header("Content-type:text/html");
header("Content-Disposition:attachment;filename=123.xls");
$array=$this->db->get("city")->result_array();
$str="id\t"."name\t"."pid\n";
foreach($array as $val){
$str.=$val['id']."\t".$val['name']."\t".$val['pid']."\n";
}
echo $str;
}
More readers interested in CodeIgniter can check the topics of this site: "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "php Excellent Development Framework Summary", "ThinkPHP Introduction Tutorial", "ThinkPHP Common Methods Summary", "Zend FrameWork Framework Introduction Tutorial", "php Object-Oriented Programming Introduction Tutorial", "php+mysql Database Operation Introduction Tutorial" and "php Common Database Operation Skills Summary"
I hope this article is helpful to the PHP programming based on CodeIgniter framework.