在处理Excel文件,批量导入数据时,首先要配置所需要的jar包, 基于Spring MVC和Maven,在pom.xml中添加:
<span style="white-space:pre"> </span><dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
在jsp页面中:
<div class="form-group">
<form class="form-horizontal" method="post" action="${path}/master/child/importChild" id="fileUpload" name="fileUpload" enctype="multipart/form-data">
<input class="form-control" type="file" id="excelFile" name="file"/>
<button class="btn btn-success" type="submit">批量上传 <i class="fa fa-upload"></i></button>
<span style="white-space:pre"> </span></form>
</div>
在MasterChildController.java中:
@RequestMapping(value = "importChild", method = RequestMethod.POST)
public String importChild(HttpServletResponse response,MultipartHttpServletRequest request) throws Exception {
//得到上传的文件
MultipartFile fileFile = request.getFile("file");
//转换成输入流
InputStream in = fileFile.getInputStream();
//得到Excel
Workbook readWb = Workbook.getWorkbook(in);
//得到sheet
Sheet readSheet = readWb.getSheet(0);
//得到多少列
int rsColumns = readSheet.getColumns();
//得到多少行
int rsRows = readSheet.getRows();
//单元格
Cell cell ;
//实例化Child对象
Child child = new Child();
Map<Integer,String> map = new HashMap<Integer, String>();
for(int i=1;i<rsRows;i++) {
for (int j = 0; j < rsColumns; j++) {
cell = readSheet.getCell(j,i);
map.put(j, cell.getContents());
}
child.setId(Atools.getOneKeyS());
String gradesName = map.get(0);
//查询Grades对象
Map<String, Object> params = new HashMap<String, Object>();
params.put("gradesName", gradesName);
List<Grades> grades = gradesService.queryAll(params);
if(grades.size()>0 && grades.size()==1) {
child.setGradesId(grades.get(0).getId());
}
child.setChildNo(map.get(1));
child.setChildName(map.get(2));
child.setSex(map.get(3));
if(("男").equals((map.get(3)))) {
child.setSex("1");
}else if(("女").equals((map.get(3)))) {
child.setSex("0");
}else {
child.setSex("0");
}
child.setAge(Integer.parseInt(map.get(4)));
child.setBrithDay(map.get(5));
Date date = new Date();
child.setAddDate(date);
child.setDr(map.get(6));
child.setFatherName(map.get(7));
child.setFatherPhone(map.get(8));
child.setFatherWork(map.get(9));
child.setMotherName(map.get(10));
child.setMotherPhone(map.get(11));
child.setMotherWork(map.get(12));
child.setAddress(map.get(13));
child.setComments(map.get(14));
childService.addBean(child);
}
return reList;
}
综上所述:即可完成Java web中form表单提交Excel文件,批量上传数据!