excel导入导出

来源:互联网 发布:网络贷款诈骗方式 编辑:程序博客网 时间:2024/05/16 08:27
  1. public function excel_put(){  
  2.     //先做一个文件上传,保存文件  
  3.     $path=$_FILES['file'];  
  4.     $filePath = "uploads/".$path["name"];  
  5.     move_uploaded_file($path["tmp_name"],$filePath);  
  6.     //默认用excel2007读取excel,若格式不对,则用之前的版本进行读取  
  7.     //表格字段名字  
  8.     $data=array('B'=>'name','C'=>'pwd','D'=>'money1','E'=>'salt');  
  9.     $tablename='user1';//表名字  
  10.     $this->excel_fileput($filePath,$data,$tablename);      
  11. }  
  12. private function excel_fileput($filePath,$data,$tablename){  
  13.     $this->load->library("phpexcel");//ci框架中引入excel类  
  14.     $PHPExcel = new PHPExcel();  
  15.     $PHPReader = new PHPExcel_Reader_Excel2007();  
  16.     if(!$PHPReader->canRead($filePath)){  
  17.         $PHPReader = new PHPExcel_Reader_Excel5();  
  18.         if(!$PHPReader->canRead($filePath)){  
  19.             echo 'no Excel';  
  20.             return ;  
  21.         }  
  22.     }  
  23.     // 加载excel文件  
  24.     $PHPExcel = $PHPReader->load($filePath);  
  25.   
  26.     // 读取excel文件中的第一个工作表  
  27.     $currentSheet = $PHPExcel->getSheet(0);  
  28.     // 取得最大的列号  
  29.     $allColumn = $currentSheet->getHighestColumn();  
  30.     // 取得一共有多少行  
  31.     $allRow = $currentSheet->getHighestRow();  
  32.   
  33.     // 从第二行开始输出,因为excel表中第一行为列名  
  34.     for($currentRow = 2;$currentRow <= $allRow;$currentRow++){  
  35.         /**从第A列开始输出*/  
  36.         //echo $allColumn;  
  37.           
  38.         for($currentColumn'A';$currentColumn<= $allColumn$currentColumn++){    
  39.             $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue();  
  40.             //print_r($val);  
  41.             //die;  
  42.               
  43.             if($currentColumn == 'A')  
  44.             {  
  45.                 //echo $val."\t";  
  46.             }else if($currentColumn <= $allColumn){  
  47.                 $data1[$currentColumn]=$val;  
  48.             }  
  49.         }  
  50.         foreach($data as $key=>$val){  
  51.             $data2[$val]=$data1[$key];  
  52.         }  
  53.         $this->db->insert($tablename,$data2);  
  54.         //print_r($data2);  
  55.         //echo "</br>";         
  56.     }  
  57.     //echo "\n";  
  58.     echo "导入成功";  
  59. }  



导出

[php] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. header("Content-type:application/vnd.ms-excel");  
  2. header("Content-Disposition:attachment;filename=123.xls");  
  3.   
  4. $array=$this->db->get("shop_address")->result_array();  
  5. $str = "Id\tName\tPid\n";  
  6. foreach ($array as $val) {  
  7.     $str .=  $val['id'] . "\t" .$val['name'] . "\t" . $val['pid'] . "\n";  
  8. }  
  9. echo $str;    
0 0
原创粉丝点击