前端代码:
<form method="post" action="xxx.action" enctype="multipart/form-data">
<input type="file" name="inputExcel" />
</form>
后端代码:
private File inputExcel;
private String inputExcelFileName;
private String inputExcelContentType;
补上相应的setter和getter方法,
详细导入方法体:
public void inputExcel() throws Exception{
InputStream is = null;
Workbook workbook = null;
if(inputExcel!=null){
String fileType = inputExcelFileName.substring(paperFormFileName.lastIndexOf(".")+1); //获取文件后序
if("xls".equals(fileType)){
workbook = new HSSFWorkbook(new FileInputStream(inputExcel));
int sheetSize = workbook.getNumberOfSheets(); //导入Excel的页数
Sheet sheet = workbook.getSheetAt(0);
int rowSize = sheet.getLastRowNum()+1; //数据行数
for(int j = 0; j < rowSize; j++){
Row row = sheet.getRow(j);
Achievement aa = new Achievement(); //具体的一个实体类,按具体情况创建对应实体类
if (row == null) { //略过空行
continue;
}
int cellSize = row.getLastCellNum(); //表单列数。行中有多少个单元格,也就是有多少列
if (j == 0) { //第一行是标题行,不做处理,跳过
}else{ //要插入的数据行
for (int k = 0; k < cellSize; k++) {
Cell cell = row.getCell(k);
//给具体的实体赋值
if(k==0) aa.setTitle(cell.toString());
if(k==1) aa.setMagazineName(cell.toString());
if(k==2) aa.setEdition(cell.toString());
if(k==3) aa.setType(cell.toString());
}
achievementService.addAchievement(aa); //往数据库插入该实体
}
}
System.out.println("导入成功!");
}else{
System.out.println("上传的文件格式有误!");
}
}
}
相应poi包网盘链接https://pan.baidu.com/s/1Sq1U_VR7M4Y_cKPkZCDmJw
密码:lxws
有不懂的可加wechat:CL1050366731交流。