通过maven导入上传文件及解析excel的包:
①:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
②:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
一:JSP代码:定义一个input标签,type属性为file,外层定义一个from表单加上enctype="multipart/form-data"属性.具体代码如下:
<form id="QueryForm" action="${ctx}/addData/upLoad.do" method="post" enctype="multipart/form-data" onsubmit="return check();"> <div class="row"> <div class="col-sm-6" style="width: 50%;"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">请选择上传的文件:</h3> <div class="box-body"> <input id="excel_file" class="form-control" type="file" name="filename" accept="xlsx" size="80" /> </div> <span class="box-title"><c:if test="${msg !=''}">${msg}</c:if> </span> <input class="btn btn-primary pull-right" id="excel_button" type="submit" value="导入" /> </div> </div> </div> </div> </form>
二:controller层:
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.beipei.dal.dataobject.OrderformDO; import com.beipei.service.common.facade.OrderformService; @Controller @RequestMapping("/addData") public class AddDataContorller { @Value("${application.jsp.path}") private String jspPath; @Autowired private OrderformService orderformService; @RequestMapping("/addDatas.do") public String addDatas(){ return jspPath+"czgn/AddData/AddData.jsp"; } /**接收上传的文件*/ @RequestMapping("/upLoad.do") public String upLoad(@RequestParam(value="filename") MultipartFile file,Map<String, Object> map){ String msg = ""; //获取文件名 String name = file.getOriginalFilename(); //定义一个本地文件副本(路径+文件名),用来接收前端上传的文件内容容 String localfile = "/app/newFile.xlsx";//需要修改文件路径 try{ List<OrderformDO> orderformDOs = orderformService.excelImport(name, file,localfile); System.out.println(orderformDOs); msg = "解析成功,总共"+orderformDOs.size()+"条!";
}catch(Exception e){
e.printStackTrace();
msg ="导入失败......";
}
map.put("msg", msg);
return jspPath+"czgn/AddData/AddData.jsp";
}
}
三:下面是解析excel代码,通过service层调用util包内自己写的解析工具类
@Override public List<OrderformDO> excelImport(String name, MultipartFile file, String localfile) { ReadExcel ReadExcel = new ReadExcel(); List<OrderformDO> excelInfo = ReadExcel.getExcelInfo(name, file, localfile); return excelInfo; }
ReadExcel.java
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; import com.beipei.dal.dataobject.OrderformDO; public class ReadExcel { // 总行数 private int totalRows = 0; // 总条数 private int totalCells = 0; // 错误信息接收器 private String errorMsg; // 构造方法 public ReadExcel() { } // 获取总行数 public int getTotalRows() { return totalRows; } // 获取总列数 public int getTotalCells() { return totalCells; } // 获取错误信息 public String getErrorInfo() { return errorMsg; } /** * 验证EXCEL文件 * * @param filePath * @return */ public boolean validateExcel(String filePath) { if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil .isExcel2007(filePath))) { errorMsg = "文件名不是excel格式"; return false; } return true; } /** * 读EXCEL文件,获取客户信息集合 * * @param fielName * @return */ public List<OrderformDO> getExcelInfo(String fileName, MultipartFile Mfile, String localfile) { File file1 = new File(localfile);//新建文件 //转存文件,将文件转存到本地 try { Mfile.transferTo(file1); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } List<OrderformDO> list = new ArrayList<OrderformDO>(); // 初始化输入流 InputStream is = null; try { // 验证文件名是否合格 if (!validateExcel(fileName)) { return null; } // 根据文件名判断文件是2003版本还是2007版本 boolean isExcel2003 = true; if (WDWUtil.isExcel2007(fileName)) { isExcel2003 = false; } // 根据新建的文件实例化输入流 is = new FileInputStream(file1); // 根据excel里面的内容读取信息 list = getExcelInfo(is, isExcel2003); is.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { is = null; e.printStackTrace(); } } } return list; } /** * 根据excel里面的内容读取客户信息 * @param is * 输入流 * @param isExcel2003 * excel是2003还是2007版本 * @return * @throws IOException */ public List<OrderformDO> getExcelInfo(InputStream is, boolean isExcel2003) { List<OrderformDO> list = null; try { /** 根据版本选择创建Workbook的方式 */ Workbook wb = null; // 当excel是2003时 if (isExcel2003) { wb = new HSSFWorkbook(is); } else {// 当excel是2007时 wb = new XSSFWorkbook(is); } // 读取Excel里的信息 list = readExcelValue(wb); } catch (IOException e) { e.printStackTrace(); } return list; } /** * 读取Excel里面信息 * * @param wb * @return */ private List<OrderformDO> readExcelValue(Workbook wb) { // 得到第一个shell Sheet sheet = wb.getSheetAt(0); // 得到Excel的行数 this.totalRows = sheet.getPhysicalNumberOfRows(); // 得到Excel的列数(前提是有行数) if (totalRows >= 1 && sheet.getRow(0) != null) { this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells(); } List<OrderformDO> orderformDOs = new ArrayList<OrderformDO>(); // 循环Excel行数,从第二行开始。标题不入库 for (int r = 1; r < totalRows; r++) { OrderformDO orderformDO = new OrderformDO(); Row row = sheet.getRow(r).getCell(1).getRow(); if (row == null) continue; // 循环Excel的列,获取相关信息 for (int c = 0; c < this.totalCells; c++) { Cell cell = row.getCell(c); if (null != cell) { if (c == 0) { cell.setCellType(Cell.CELL_TYPE_STRING); orderformDO.setLicensenumber(cell.getStringCellValue()); } else if (c == 1) { cell.setCellType(Cell.CELL_TYPE_STRING); orderformDO.setPolicyno(cell.getStringCellValue()); } else if (c == 3) {//日期>>需要转换 if(HSSFDateUtil.isCellDateFormatted(cell)){ orderformDO.setStartdate(cell.getDateCellValue()); } } else if (c == 4) {//日期 if(HSSFDateUtil.isCellDateFormatted(cell)){ orderformDO.setEnddate(cell.getDateCellValue()); } }else if (c == 5) { if(HSSFDateUtil.isCellDateFormatted(cell)){ orderformDO.setInserttimeforhis(cell.getDateCellValue()); } }else if (c == 6) { cell.setCellType(Cell.CELL_TYPE_STRING); orderformDO.setComcode(cell.getStringCellValue()); } } } // 添加 orderformDOs.add(orderformDO); } return orderformDOs; } }
WDWUtil.java
public class WDWUtil { // @描述:是否是2003的excel,返回true是2003 public static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } // @描述:是否是2007的excel,返回true是2007 public static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } }
以上就是上传excel文件并解析,至于如何存入数据库这里不去做了,这个工具类返回的list可以直接存入库中对应字段.