TP5.0.2有關導入導出excel表格

博主之前做勤工助學系統的時候的導入導出的模板功能

先總結下幾個問題與難點:
1、execl表格類型大小的判定
2、加載模板後的每個表格的屬性(如A1、B1等)一定要確認
3、與數據庫的數據交互一定要添加事務處理
4、最後就是一些基礎的配置了
查考模板
勤工助學考勤表
學生積分統計表

首先引入庫類

use PHPExcel_IOFactory;
use PHPExcel;

導入視圖:

  <form action="{:url('/index/bmbb/importExcel')}" method="post" enctype="multipart/form-data">
  <h5>考勤數據上傳</h5>
  <input type="file" name="file"><br/>
  <input type="submit" value="導入考勤數據"  class="btn  btn-bb" style="width:200px; height:30px;" name="sub">
   <input type="submit" value="導入積分數據"  class="btn  btn-primary" style="width:200px; height:30px;"name="sub">
</form>

導入方法:

           public function importExcel(){
           	
		vendor ( "PHPExcel.PHPExcel" ); // 獲取PHPExcel類
		$excel = new \PHPExcel ();
		
		$file = request ()->file ( 'file' );
		
		if(empty($file)){
		   	$this->error("文件不能爲空","index/bmbb/import"); 
		}
		    
		$info = $file->validate ( [ 
				'size' => 15678,
				'ext' => 'xlsx,xls,csv' 
		] )->move ( ROOT_PATH . 'public' . DS . 'excel' );

		if ($info) {
			$exclePath = $info->getSaveName (); // 獲取文件名
			$file_name = ROOT_PATH . 'public' . DS . 'excel' . DS . $exclePath; // 上傳文件的地址
			$objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
			$obj_PHPExcel = $objReader->load ( $file_name, $encode = 'utf-8' ); // 加載文件內容,編碼utf-8
			                                                                    // echo "<pre>";
			$excel_array = $obj_PHPExcel->getsheet ( 0 )->toArray (); // 轉換爲數組格式
			$arr = reset ( $excel_array );//獲得標題
			$yeararr=explode("年",trim($arr[0]));  //切割字符串獲得日期
			$moutharr=explode("月",substr(trim($arr[0]), 7));
			$day=explode("日",substr($arr[0], 11));

			if((float)$moutharr[0]<10){
				$moutharr[0]="0".$moutharr[0];
			}
			$date=$yeararr[0]."-".$moutharr[0];  //年月
			for ($i=0;$i<3;$i++){ //刪除不需要的數組
				unset($excel_array[$i]);
			}
			
			$arr=array_values($excel_array);//重新建立索引
			$mesarr = reset ( $excel_array );//拿第一條數組  下表4開始是日期1,34爲31
			unset ( $arr [0] );
			$arr=array_values($arr);
			//判斷要導入的文件
			if(input('sub')=="導入考勤數據"){
			    $trans_result = false;
			    
			try{
			Db::startTrans();
			foreach ($arr as $k =>$v){
				$res["status"]="審覈通過";
				for ($i=4;$i<35;$i++){
					if($v[$i]!=null){
						$res["studentId"]=$v[2];
						$res["worktime"]=(float)$v[$i];
						$res["date"]=$date."-".$v[$i]." ".date("H:i:s");
						$res["admin"]=$v[38];
						$list=Db::table('sign')
						->insert($res);
					
					}
				}
			}}
			catch (\Exception $e) {
				  $trans_result = false;
				  //判斷中間是否有錯誤	
			}
			}
			
			else if(input('sub')=="導入積分數據"){
			$date=$yeararr[0]."-".$moutharr[0]."-".$day[0];//日
			 $trans_result = false;
			try{
			Db::startTrans();
			foreach ($arr as $k =>$v){
				if($v[1]!=null){
				$data["xh"]=$v[1];//取出學號
				$data["xzjf"]=$v[2];//取出新增積分
				$data["bz"]=$v[3];//取出備註
                $data['shij']=$date;
				$list=Db::table('xsjfjlb')
				->insert($data);
				}
			}
			}catch (\Exception $e) {
				$trans_result = false;//判斷中間是否有錯誤
			}
			
}

				if ($trans_result === false) {
					Db::rollback();
				
					$this->error('導入失敗,格式錯誤','index/Bmbb/import');
				} else {
					Db::commit();
					unset($info);
					//一定要unset之後才能進行刪除操作,否則請求會被拒絕
					$this->success('導入成功','index/Bmbb/import');
				} 

			
     }

           }

導出模板視圖:
導出模板的視圖

 <div class="col-lg-3"><input type="submit" name="sub" value="考勤彙總表下載" class="btn  btn-bb" style="width:200px; height:50px;"></div>
              <div class="col-lg-2"><input type="submit" name="sub" value="學生積分彙總表下載" class="btn  btn-primary" style="width:250px; height:50px;"></div>

方法函數:

	public function exportAll() // 下載報表模板
{
		vendor ( "PHPExcel.PHPExcel.PHPExcel" );
		vendor ( "PHPExcel.PHPExcel.Writer.IWriter" );
		vendor ( "PHPExcel.PHPExcel.Writer.Abstract" );
		vendor ( "PHPExcel.PHPExcel.Writer.Excel5" );
		vendor ( "PHPExcel.PHPExcel.Writer.Excel2007" );
		vendor ( "PHPExcel.PHPExcel.IOFactory" );
		
		// 判斷要下載的模板
		if (input ( 'sub' ) == "考勤彙總表下載") {
			
			$temPath = iconv ( 'utf-8', 'gb2312', 'temp/1.xlsx' ); // 以public/index.php爲參照算路徑
			$newname = "勤工助學模板.xlsx";
			$phpexcel = PHPExcel_IOFactory::createReader ( "Excel2007" )->load ( $temPath );
			$year = input ( 'year' );
			$month = input ( 'month' );
			
			$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'A1', $year . "年" . $month . "月勤工助學固定崗位考覈彙總" ); // 標題頭部
			$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'E3', "日期" ); // 標題頭部
			
			$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'A3', "部門名稱(蓋章):" . input ( 'xueyuan' ) ); // 標題頭部
			$data ['status'] = "審覈通過";
			$data ['xueyuan'] = input ( 'xueyuan' );
			
			$list = db ( 'sign' )->where ( $data )->join ( "zhb", "zhb.zh=sign.studentId" )->join ( "xsxx", "sign.studentId=xsxx.xh" )->field ( 'studentId,zhb.xm,jhzh' )->group ( 'studentId,zhb.xm,jhzh' )->select ();
			if (floatval ( $month ) < 10) {
				$month = "0" . $month;
			}
			$n = 5; // A5開始
			$index = 1; // 序號
			$arr = array (
					'E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB,AC,AD,AE,AF,AG,AH,AI' 
			);
			$arr = explode ( ",", $arr [0] ); // 1 到 31
			
			foreach ( $list as $k => $v ) {
				// 單次循環出學生信息,這裏數據庫設計有問題
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'A' . $n, $index ); // 序號
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'B' . $n, $v ['xm'] ); // 姓名
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'C' . $n, $v ['studentId'] ); // 學號
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'D' . $n, $v ['jhzh'] ); // 建行銀行
				                                                                    
				// 內嵌循環
				$data2 ['studentId'] = $v ['studentId'];
				$data2 ['date'] = [ 
						'like',
						$year . '-' . $month . '%' 
				];
				
				$data2 ['status'] = "審覈通過";
				$list2 = db ( 'sign' )->where ( $data2 )->join ( 'gwb', 'gwb.xh=sign.studentId' )->join ( 'mathmoney', 'mathmoney.gwlx=gwb.gwlx' )->field ( 'studentId,worktime,date,mathmoney.gwlx,mathmoney.hour,mathmoney.max' )->select ();
				foreach ( $list2 as $k2 => $v2 ) {
					$str = explode ( "-", $v2 ['date'] );
					$str = explode ( ' ', $str [2] ); // $str[0]爲當月日期
					$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( $arr [$str [0] - 1] . $n, $v2 ['worktime'] ); // 工作當日
					$sum += $v2 ['worktime'];
				}
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( "AJ" . $n, $sum ); // 當月工作總時長
				                                                               // dump($sum);
				if ($v2 ['gwlx'] == '臨時性輪崗') {
					$money = $sum * $v2 ['hour'];
					if ($money > $v2 ['max']) {
						$money = $v2 ['max'];
					}
				} else {
					$money = $sum * $v2 ['hour'];
					if ($money > $v2 ['max']) { // 超標
						$money = $v2 ['max'];
					} else {
						if ($sum < 20) {
							$money = $money * 0.9; // 未達到優
						}
					}
				}
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( "AK" . $n, $money ); // 當月工作總時長
				if ($sum >= 20) {
					$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( "AL" . $n, '優' ); // 當月工作表現
				} else {
					$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( "AL" . $n, '良' ); // 當月工作表現
				}
				
				$sum = 0;
				$n ++;
				$index ++;
			}
		} else if (input ( 'sub' ) == "學生積分彙總表下載") {
			$temPath = iconv ( 'utf-8', 'gb2312', 'temp/2.xlsx' ); // 以public/index.php爲參照算路徑
			$newname = "學生積分模板.xlsx";
			$phpexcel = PHPExcel_IOFactory::createReader ( "Excel2007" )->load ( $temPath );
			
			$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'A3', "部門名稱(蓋章):" . input ( 'xueyuan' ) );
			$where ['xueyuan'] = input ( 'xueyuan' );
			$jflist = db ( "xsjfjlb" )->
			// ->where($con)
			
			join ( 'xsxx', 'xsxx.xh=xsjfjlb.xh' )->field ( 'xsxx.xh,SUM(xzjf) as jf,bz,xueyuan' )->where ( $where )->group ( 'xh' )->select ();
			
			$num = 1;
			$p = 5;
			foreach ( $jflist as $kjf => $k ) {
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'A' . $p, $num );
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'B' . $p, $k ['xh'] );
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'C' . $p, $k ['jf'] );
				$phpexcel->setActiveSheetIndex ( 0 )->setCellValue ( 'D' . $p, $k ['bz'] );
				
				$num ++;
				$p ++;
			}
		}
		
		// $temPath = "temp/勤工助學考勤表彙總表.xls";//以public/index.php爲參照算路徑
		// 檢查文件路徑
		if (! file_exists ( $temPath )) {
			$this->error ( '模板不存在' );
			return;
		}
		// 加載模板
		
		$filename = iconv ( 'utf-8', 'gb2312', $newname );
		$objWriter = new \PHPExcel_Writer_Excel2007 ( $phpexcel );
		$this->outPut ( $filename, "Excel2007" );
		$objWriter->save ( 'php://output' );
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章