一:
二: PHPExcel: Github上可以下载此插件包,用法如下:
前端:
//上传阅卷员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"});
后端:
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');//禁止缓存}