1. 程式人生 > >PHPExcel整合對資料匯入和匯出

PHPExcel整合對資料匯入和匯出


<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/8/15
 * Time: 9:07
 */
class User extends CI_Controller {
     public function __construct(){
         parent::__construct();
         $this->load->database();
     }
    public function index(){
        $this->load->view('head');
        $this->load->view('admin/user/upload');
        $this->load->view('footer');
    }
     public function export(){
         $this->load->library('PHPExcel');
         $objPHPExcel=new PHPExcel();
         $sql="select id,username,password,email,mobile,create_time from user";
         $query=$this->db->query($sql);
         $data=$query->result_array();
         $objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007");
//設定excel的屬性:
//合併單元格
         $objPHPExcel->getActiveSheet()->mergeCells('A1:F1');
         $objPHPExcel->getActiveSheet()->mergeCells('A2:F2');
//設定表頭行高
         $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(35);
         $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(25);
//設定font
         $objPHPExcel->getActiveSheet()->getStyle('A:F')->getFont()->setName('Microsoft YaHei UI');
         $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(16);
         $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);
         $objPHPExcel->getActiveSheet()->getStyle('A:F')->getFont()->setSize(12);
//設定預設行高
         $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20);
//設定列寬
         $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(8);
         $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
         $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(25);
         $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(35);
         $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
         $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(45);
//設定表頭對齊方式
         $objPHPExcel->getActiveSheet()->getStyle('A1:A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
         $objPHPExcel->getActiveSheet()->getStyle('A1:A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//設定水平左對齊
         $objPHPExcel->getActiveSheet()->getStyle('A:J')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//所有垂直居中
         $objPHPExcel->getActiveSheet()->getStyle('A:J')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//填入主標題
         $objPHPExcel->getActiveSheet()->setCellValue('A1', '測試');
//填入副標題
         $objPHPExcel->getActiveSheet()->setCellValue('A2', '測試(匯出日期:' . date('Y-m-d H:i:s', time()) . ')');
//填入表頭
         $objPHPExcel->getActiveSheet()->setCellValue('A3', '序號');
         $objPHPExcel->getActiveSheet()->setCellValue('B3', '使用者名稱');
         $objPHPExcel->getActiveSheet()->setCellValue('C3', '密碼');
         $objPHPExcel->getActiveSheet()->setCellValue('D3', '郵箱');
         $objPHPExcel->getActiveSheet()->setCellValue('E3', '手機號');
         $objPHPExcel->getActiveSheet()->setCellValue('F3', '註冊時間');
//寫資料到表格裡面去
         foreach ($data as $key => $value) {
             $i = $key + 1;//表格是從1開始的
             $objPHPExcel->getActiveSheet()->setCellValue('A' . ($i + 3), $value['id']);
             $objPHPExcel->getActiveSheet()->setCellValue('B' . ($i + 3), $value['username']);
             $objPHPExcel->getActiveSheet()->setCellValue('C' . ($i + 3), $value['password']);
             $objPHPExcel->getActiveSheet()->setCellValue('D' . ($i + 3), $value['email']);
             $objPHPExcel->getActiveSheet()->setCellValue('E' . ($i + 3), $value['mobile']);
             $objPHPExcel->getActiveSheet()->setCellValue('F' . ($i + 3), $value['create_time']);
         }
//下載這個表格,在瀏覽器輸出
         $filename = '測試';
         $outputFileName = $filename . ".xls";
         header("Content-Type: application/force-download");
         header("Content-Type: application/octet-stream");
         header("Content-Type: application/download");
         header('Content-Disposition:attachment;filename="' . $outputFileName . '"');  //到檔案
////header(‘Content-Disposition:inline;filename="‘.$outputFileName.‘"‘);  //到瀏覽器
         header("Content-Transfer-Encoding: binary");
         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Pragma: no-cache");
         $objWriter->save('php://output');
     }
     public function importExcel(){
         //判斷是否符合檔案格式
         $allowedExts = array("xls", "xlsx", "csv");
         $temp = explode(".", $_FILES["myfile"]["name"]);
         $extension = end($temp);     // 獲取檔案字尾名
         $filePath = '';
         if(!in_array($extension,$allowedExts)){
             echo "檔案格式不對";exit();
         }
         if(is_uploaded_file($_FILES['myfile']['tmp_name'])){
             $savePath= './asset/upload/';
             $str =date('Ymdhis');
             $fileName=$str.'.'.pathinfo($_FILES['myfile']['name'],PATHINFO_EXTENSION);
             //移動到指定的目錄
             if(move_uploaded_file($_FILES['myfile']['tmp_name'],$savePath.$fileName)){
                 echo "<script>alert('上傳成功')</script>";
             }
              $this->load->library('PHPExcel');
             if (!file_exists($savePath.$fileName)) {
                 die('no file!');
             }
             $filePath="./asset/upload/".$fileName;
             $PHPReader = new PHPExcel_Reader_Excel2007();
             if (!$PHPReader->canRead($filePath)) {
                 $PHPReader = new PHPExcel_Reader_Excel5();
                 if (!$PHPReader->canRead($filePath)) {
                     echo 'no Excel';
                     return;
                 }
             }
             $PHPExcel = $PHPReader->load($filePath);
             //讀取excel檔案中的第一個工作表
             $sheet = $PHPExcel->getSheet(0);
                //取得最大的列號
             $allColumn = $sheet->getHighestColumn();
             //取得最大的行號
             $allRow = $sheet->getHighestRow();
             for($currentRow=3;$currentRow<$allRow;$currentRow++){
                 $name=$PHPExcel->getActiveSheet()->getCell('A'.$currentRow)->getValue();
                 $password=$PHPExcel->getActiveSheet()->getCell('B'.$currentRow)->getValue();
                 $email=$PHPExcel->getActiveSheet()->getCell('C'.$currentRow)->getValue();
                 $mobile=$PHPExcel->getActiveSheet()->getCell('D'.$currentRow)->getValue();
                 //插入資料庫
                 $res=$this->db->insert('user',['username'=>$name,'password'=>$password,'email'=>$email,'mobile'=>$mobile,'create_time'=>date('Y-m-d H:i:s',time())]);
             }
             if($res){
                 echo "匯入成功";
             }else{
                 echo "匯出失敗";
             }
         }
     }
}