java excel 匯入試題
阿新 • • 發佈:2018-12-08
js讀取匯入的名稱到對應的位置顯示
$(function() { $('#myFile').on('change', function() { var originName = $(this).val(); var fileName = originName.substring(originName.lastIndexOf('\\')+1); fileName = '<span class="am-badge">' + fileName + '</span>'; $('#file-list').html(fileName); }); }); function importExcel() { var myFile = $("#myFile").val(); if (myFile.length <= 0) { dialogFun("批量匯入試題", "請選擇匯入內容", 0); return false; } $("#importP").submit(); }
html程式碼實現
<div class="am-u-sm-8 am-u-md-6"> <div class="am-form-group am-form-file"> <button class="am-btn am-btn-danger am-btn-sm" type="button"> <i class="am-icon-cloud-upload"></i> 選擇要上傳的檔案</button> <input id="myFile" type="file" value="" accept=".xls" name="myFile"/> </div> <div id="file-list"></div> </div> <div class="am-hide-sm-only am-u-md-4"></div>
<form action="/admin/quest/importExcel" method="post" id="importP" enctype="multipart/form-data" class="am-form">
</form>
後臺程式碼實現
/** * 批量匯入試題 * /admin/quest/importExcel * @param request * @param file * @return */ @RequestMapping("/quest/importExcel") public String importExcel(HttpServletRequest request, @RequestParam("myFile") MultipartFile file) { try { Long companyId = SingletonLoginUtils.getCurrentCompanyId(request); logger.info("myFile:" + file.getName()); examQuestionService.updateImportQuestionExcel(file, companyId); request.setAttribute("msg", "操作成功"); } catch (BaseException e) { logger.error("QuestionAction.importExcel", e); request.setAttribute("msg", e.getMessage()); return msgError; } catch (RecordFormatException e) { logger.error("QuestionAction.importExcel", e); request.setAttribute("msg", "圖片格式化失敗,請勿匯入圖片"); return msgError; } catch (Exception e) { logger.error("AdminQuestionAction.randomQuestion", e); request.setAttribute("msg", e.getMessage()); return msgError; } return "/common/success"; }
方法實現
/**
* 批量匯入試題
* @param file 檔案
* @param companyId 公司ID
* @return
* @throws Exception
*/
public String updateImportQuestionExcel(MultipartFile file, Long companyId) throws Exception {
// datalist拼裝List<String[]> deadliest,
HSSFWorkbook wookbook = new HSSFWorkbook(file.getInputStream());
HSSFSheet sheet = wookbook.getSheetAt(0);
// 指的行數,一共有多少行+
int rows = sheet.getLastRowNum();
Calendar calendar = Calendar.getInstance();
List<NxbSubject> subjectR = nxbSubjectService.getSubjectListByType(SubjectType.EXAM.toString());
for (int i = 1; i <= rows; i++) {
// 讀取左上端單元格
HSSFRow row = sheet.getRow(i);
// 行不為空
if (row != null) {
// 獲取到Excel檔案中的所有的列
int maxcell = row.getLastCellNum();
// **讀取cell**
String content = getCellValue(row.getCell((short) 0));// 試題內容
String subjectId = getCellValue(row.getCell((short) 1));// 專業ID
String pointId = trimZero(getCellValue(row.getCell((short) 2)));// 考點
String isAsr = getCellValue(row.getCell((short) 3));// 正確答案
String type = getCellValue(row.getCell((short) 4));// 題型
String level = trimZero(getCellValue(row.getCell((short) 5)));// 試題難度
String analyze = getCellValue(row.getCell((short) 6));// 解析
String optionA = getCellValue(row.getCell((short) 7)); // A
String optionB = getCellValue(row.getCell((short) 8)); // B
String optionC = getCellValue(row.getCell((short) 9)); // C
String optionD = getCellValue(row.getCell((short) 10)); // D
String optionE = getCellValue(row.getCell((short) 11)); // E
String optionF = getCellValue(row.getCell((short) 12)); // F
String optionG = getCellValue(row.getCell((short) 13)); // D
if(StringUtils.isEmpty(content)&&
StringUtils.isEmpty(subjectId)&&
StringUtils.isEmpty(isAsr)&&
StringUtils.isEmpty(type)&&
StringUtils.isEmpty(level)&&
StringUtils.isEmpty(analyze)){
break;
}
// 試題內容,專業,正確答案,試題型別,試題難度
if (StringUtils.isEmpty(content) || StringUtils.isEmpty(subjectId) || StringUtils.isEmpty(isAsr) || StringUtils.isEmpty(type) || StringUtils.isEmpty(level)) {
throw new BaseException(
"第" + i + "行,試題內容為<" + content + ">的那條資料資料不能為空(試題內容,專業,正確答案,試題型別,試題難度)");
}
logger.info("試題型別:" + type);
switch (type) {
case "單選":
type = "1";
break;
case "多選":
type = "2";
break;
case "判斷":
type = "3";
break;
case "不定項":
type = "5";
break;
default:
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料試題型別不正確(試題型別只能輸入單選,多選,判斷,不定項)");
}
// 專業ID必須是大於0的正整數
if (!StringUtils.isNumber(subjectId)||Long.parseLong(subjectId)<=0) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料專業ID必須是大於0的正整數");
}
//該 專業ID必須是該公司所有
NxbQuerySubject nxbQuerySubject=new NxbQuerySubject();
nxbQuerySubject.setCompanyId(companyId);
nxbQuerySubject.setSubjectId(Long.parseLong(subjectId));
List<NxbSubject> subjectList = nxbSubjectDao.getSubjectList(nxbQuerySubject);
if (subjectList==null||subjectList.size()==0) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料專業ID必須是該分公司所擁有的");
}
// // 考點必須是大於0的正整數
// if (!StringUtils.isNumber(pointId)||Long.parseLong(pointId)<=0) {
// throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料考點ID必須是大於0的正整數");
// }
// 試題難度
logger.info("試題難度:" + level);
switch (level) {
case "一級":
level = "1";
break;
case "二級":
level = "2";
break;
case "三級":
level = "3";
break;
default:
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料的試題難度必須是一級、二級、三級其中的一個");
}
int typeInt = ConvertUtils.objectToInt(type);
// 如果為判斷題最多2個選項
if (typeInt == 3) {
if (StringUtils.isEmpty(optionA) || StringUtils.isEmpty(optionB)) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料為判斷題,選項A或選項B不能為空");
}
if (StringUtils.isNotEmpty(optionD) || StringUtils.isNotEmpty(optionE)
|| StringUtils.isNotEmpty(optionF) || StringUtils.isNotEmpty(optionG)) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料為判斷題,選項D,E,F,G必須為空");
}
}
// 如果不是判斷題,選項必須大於等於4個小於等於7個選項
if (typeInt != 3) {
if (StringUtils.isEmpty(optionA) || StringUtils.isEmpty(optionB) ) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料為選擇題,選項A,B不能為空");
}
}
// 如果為多選題正確答案必須在兩個以上
if (typeInt == 2 && isAsr.trim().length() < 2) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料的為多選題,正確答案必須在兩個以上(例:AB)");
}
// 如果為單選題或者判斷題答案只能有一個
if (typeInt == 1 || typeInt == 3) {
if (isAsr.trim().length() > 1) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料的正確答案只能有一個(例:A)");
}
}
// 選項不能超過7個字元
if (isAsr.trim().length() > 7) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料正確答案不能超過7個字元(例AB)");
}
// 驗證正確答案不能輸入其他字元
char[] asr = isAsr.toString().trim().toCharArray();
String asrStr = "";
for (int y = 0; y < asr.length; y++) {
asrStr += asr[y] + ",";
if ("ABCDEFG".indexOf(String.valueOf(asr[y])) == -1) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料正確答案輸入字元格式不正確(例AB)");
}
}
isAsr = asrStr.substring(0, asrStr.length() - 1);
Question question = new Question();
question.setStatus(1);
// 試題型別
int qstType = typeInt;
question.setQstType(qstType);
// 驗證專案ID
Long subjectIdLong = Long.valueOf(subjectId.trim());
for (int x = 0; x < subjectR.size(); x++) {
if (subjectR.get(x).getSubjectId().longValue() == subjectIdLong.longValue()) {
question.setSubjectId(subjectIdLong);
break;
}
}
// 如果輸入的專業不匹配
if (question.getSubjectId() == null || question.getSubjectId().intValue() <= 0) {
throw new BaseException("第" + i + "行,試題內容為<" + content + ">的那條資料的專業id不匹配");
}
// 驗證考點
if(StringUtils.isNotEmpty(pointId)){
Long pointIdLong = Long.valueOf(pointId.trim());
ExamPoint point = new ExamPoint();
point.setSubjectId(subjectIdLong);
point.setId(pointIdLong);
List<ExamPoint> pointList = pointDao.getPointList(point);
if (!pointList.isEmpty()) {
question.setPointId(pointIdLong);
}
}
//調整答案順序
if(typeInt==2){
String[] chars = isAsr.split(",");
Arrays.sort(chars);
if(ObjectUtils.isNotNull(chars)&&chars.length>1){
StringBuilder isAsrs=new StringBuilder();
for (String s:chars){
isAsrs.append(s);
isAsrs.append(",");
}
isAsr=isAsrs.substring(0,isAsrs.length()-1);
}
}
question.setLevel(ConvertUtils.objectToInt(level));
question.setQstContent(content);
question.setIsAsr(isAsr);
question.setQstAnalyze(analyze);
question.setAddTime(new Date());
question.setAuthor("admin");
question.setCompanyId(companyId); // 公司ID
questionDao.addOneQuestion(question);
int AASC = 64;
List<String> str = new ArrayList<String>();
// 把選項的值放入list中
str.add(optionA);
str.add(optionB);
str.add(optionC);
str.add(optionD);
str.add(optionE);
str.add(optionF);
str.add(optionG);
List<QuestionOption> optionList = new ArrayList<>();
for (int k = 0; k < str.size(); k++) {
// 如果選項為空字串則不新增該選項
if (!"".equals(str.get(k).trim())) {
QuestionOption option = new QuestionOption();
option.setAddTime(new Date());
option.setOptAnswer(question.getIsAsr());
option.setOptContent(str.get(k).trim());
option.setQstId(question.getId());
char data[] = { backchar(AASC += 1) };
option.setOptOrder(String.valueOf(data));
optionList.add(option);
}
}
Map<String, List<QuestionOption>> map = new HashMap<>();
map.put("optionList", optionList);
optionDao.addOptionBatch(map);
}
}
return null;
}
/**
* 獲得Hsscell內容
*
* @param cell
* @return
*/
public String getCellValue(HSSFCell cell) {
String value = "";
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
break;
case HSSFCell.CELL_TYPE_NUMERIC:
value = cell.getNumericCellValue() + "";
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue().trim();
break;
default:
value = "";
break;
}
}
return value.trim();
}
String trimZero(String str) {
if (StringUtils.isNotEmpty(str)) {
return str.replace(".0", "");
}
return str;
}
工具類
public abstract class ConvertUtils {
private static final DecimalFormat simpleFormat = new DecimalFormat("####");
public static final boolean objectToBoolean(Object o) {
return o != null?Boolean.valueOf(o.toString()).booleanValue():false;
}
public static final int objectToInt(Object o) {
if(o instanceof Number) {
return ((Number)o).intValue();
} else {
try {
if(o == null) {
return -1;
} else {
BigDecimal bigDecimal = new BigDecimal(o.toString());
bigDecimal.intValue();
return bigDecimal.intValue();
}
} catch (Exception var2) {
var2.printStackTrace();
return -1;
}
}
}
}
試題模板如下所示:
專案中所用的依賴為:
<!-- poi excel -->
<dependency>
<groupId>poi</groupId>
<artifactId>poi-2.5.1-final</artifactId>
<version>20040804</version>
</dependency>
<!-- poi excel -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.3</version>
</dependency>