第一步:导入jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
第二步:创建数据模型
public class QuestionExcel {
private String label; // 标签,分类,以逗号分隔
private Integer type; // 题目类型
private String content; // 题干
private String answer; // 答案 判断题,单选题,多选题
private Double score; // 分值
private List<String> options; // 选项
......
}
第三步:jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/jquery-1.7.1.js"></script>
<script type="text/javascript" src="../js/jquery.form.js"></script>
<title>题目列表</title>
<body>
<div id="content" class="mainContent">
<form method="POST" enctype="multipart/form-data" id="form1" action="uploadExcel/form">
<label>导入题目: </label>
<input id="upfile" type="file" name="upfile">
<input type="button" value="提交" id="btn" name="btn" >
</form>
<div id="questionGrid" class="maingrid"></div>
</div>
</body>
<script type="text/javascript">
/* ajax 方式上传文件操作 */
$(document).ready(function(){
$("#btn").ligerButton();
$("#btn").click(function(){
if(checkData()){
$('#form1').ajaxSubmit({
url:'questionUpload.do',
dataType: 'text',
success: resutlMsg,
error: errorMsg
});
function resutlMsg(msg){
alert(msg);
$("#upfile").val("");
}
function errorMsg(){
alert("导入excel出错");
}
}
});
});
//JS校验form表单信息
function checkData(){
var fileDir = $("#upfile").val();
var suffix = fileDir.substr(fileDir.lastIndexOf("."));
if("" == fileDir){
alert("选择需要导入的Excel文件");
return false;
}
if(".xls" != suffix && ".xlsx" != suffix ){
alert("选择Excel格式的文件导入");
return false;
}
return true;
}
</script>
</html>
第四步:Controller
@RequestMapping(value="/questionUpload")
public void ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
//MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
InputStream in =null;
List<List<Object>> listob = null;
MultipartFile file = multipartRequest.getFile("upfile");
if(file.isEmpty()){
throw new Exception("文件不存在");
}
in = file.getInputStream();
listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
// 获取Excel中的数据
List<QuestionExcel> questionExcelList = new ArrayList<>();
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
if(lo == null || lo.size() == 0)
continue;
String label = String.valueOf(lo.get(0));
String type = String.valueOf(lo.get(1));
String content = String.valueOf(lo.get(2));
String answer = String.valueOf(lo.get(3));
String score = String.valueOf(lo.get(4));
List<String> options = new ArrayList<>();
for(int j = 5; j < lo.size(); j++){
String option = String.valueOf(lo.get(j));
options.add(option);
}
//
int typeVal = 1;
if("判断题".equals(type)){
typeVal = 1;
}
else if("单选题".equals(type)){
typeVal = 2;
}
else if("多选题".equals(type)){
typeVal = 3;
}
QuestionExcel questionExcel = new QuestionExcel();
questionExcel.setLabel(label);
questionExcel.setType(typeVal);
questionExcel.setContent(content);
questionExcel.setAnswer(answer);
questionExcel.setScore(Double.parseDouble(score));
questionExcel.setOptions(options);
questionExcelList.add(questionExcel);
System.out.println("打印信息-->"+questionExcel.toString());
}
// TODO创建题目和选项
PrintWriter out = null;
response.setCharacterEncoding("utf-8"); //防止ajax接受到的中文信息乱码
out = response.getWriter();
out.print("题目导入完成");
out.flush();
out.close();
}
第五步:ImportExcelUtil.java
public class ImportExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
* @param in,fileName
* @return
* @throws IOException
*/
public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getCellValue(cell));
}
list.add(li);
}
}
in.close();
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
public Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
}
第六步:导入Excel文件