一: PHP將數據導出Excel表中(投機型)php
二: PHPExcel: Github上能夠下載此插件包,用法以下:html
前端:前端
//上傳閱卷員Excel文件 $("#upload_member").click(function (e) { e.preventDefault(); var members_form = document.getElementById("members_form"); var formData = new FormData(members_form); $.ajax({ url: "/marking_manage/ajax_upload_members", method: "post", data: formData, dataType: "JSON", success: function (data) { //這裏顯示php腳本讀取excel文件處理後返回的值 }, //jquery使用FormData時必須設置下面兩項,不然不會成功 processData: false, // 不處理數據 contentType: false // 不設置內容類型 }) }); //下載導入閱卷員模板 $("#download_excel").click(function (e) { self.location.href = "/marking_manage/ajax_download_members" });
後端:jquery
public function ajax_upload_members() { require_once(APPPATH . 'libraries/PHPExcel.php'); require_once(APPPATH . 'libraries/PHPExcel/IOFactory.php'); date_default_timezone_set("PRC"); $file = $_FILES; $fileName = $file['members']["tmp_name"]; $inputFileType = PHPExcel_IOFactory::identify($fileName); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($fileName); // 肯定要讀取的sheet $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); //讀取賬號 $accounts = array();//保存文件中的全部賬號,實際就是A列中的全部以t開頭的賬號 for ($row = 1; $row <= $highestRow; $row++) { $rowData = $sheet->rangeToArray('A' . $row . ':' . "A" . $row); $account = strtolower($rowData[0][0]); if (preg_match("/^t\d+/", $account)) { $accounts[] = $account; } } $accounts = array_unique($accounts); //過濾賬號並返回 $this->load->model("school_admin_model"); $retval = array();//返回值 foreach ($accounts as $account) { $teacher_info = $this->school_admin_model->get_admin_by_where(array("account"=>$account)); // $retval[$teacher_info["school_id"]][] = array("account"=>$teacher_info["account"], "teacher_name"=>$teacher_info['teacher_name']); $retval[$teacher_info["school_id"]][] = $teacher_info["id"]; } dexit($retval); } //下載閱卷員模板 public function ajax_download_members() { require_once(APPPATH . 'libraries/PHPExcel.php'); require_once(APPPATH . 'libraries/PHPExcel/IOFactory.php'); date_default_timezone_set("PRC"); $objPHPExcel = new PHPExcel(); $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', '賬號') ->setCellValue('B1', '姓名') ->setCellValue('C1', '學校'); // 設置第一個sheet爲工做的sheet $objPHPExcel->setActiveSheetIndex(0); // 保存Excel 2007格式文件 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');//若是第二個參數是"Excel5"則生成2003版本的excel文件 browser_export('xxx','browser_excel07.xls');//輸出到瀏覽器 $objWriter->save('php://output'); } function browser_export($type, $filename) { if ($type == "Excel5") { header('Content-Type: application/vnd.ms-excel');//告訴瀏覽器將要輸出excel03文件 } else { header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告訴瀏覽器數據excel07文件 } header('Content-Disposition: attachment;filename="' . $filename . '"');//告訴瀏覽器將輸出文件的名稱 header('Cache-Control: max-age=0');//禁止緩存 }