1.导入poi相关jar包
对于只操作2003及以前版本的excel,只需要导入poi-XXX.jar ,如果还需要对2007及以后版本进行操作,则需要导入
poi-ooxml-XXX.jar
poi-ooxml-schemas-XXX.jar
Maven方式
1 <dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi</artifactId> 4 <version>3.17</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.apache.poi</groupId> 9 <artifactId>poi-ooxml</artifactId>10 <version>3.17</version>11 </dependency>
2.读取excel文件
ImportExcel工具类
1 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 2 import org.apache.poi.ss.usermodel.*; 3 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 4 5 import java.io.InputStream; 6 import java.util.ArrayList; 7 import java.util.HashMap; 8 import java.util.List; 9 import java.util.Map;10 11 public class ImportExcel {12 // abc.xls
13 public static boolean isXls(String fileName){14 // (?i)忽略大小写15 if(fileName.matches("^.+\\.(?i)(xls)$")){16 return true;17 }else if(fileName.matches("^.+\\.(?i)(xlsx)$")){18 return false;19 }else{20 throw new RuntimeException("格式不对");21 }22 }23 24 public static List<Map<String, Object>> readExcel(String fileName, InputStream inputStream) throws Exception{25 26 boolean ret = isXls(fileName);27 Workbook workbook = null;28 // 根据后缀创建不同的对象29 if(ret){30 workbook = new HSSFWorkbook(inputStream);31 }else{32 workbook = new XSSFWorkbook(inputStream);33 }34 Sheet sheet = workbook.getSheetAt(0);35 // 得到标题行36 Row titleRow = sheet.getRow(0);37 38 int lastRowNum = sheet.getLastRowNum();39 int lastCellNum = titleRow.getLastCellNum();40 41 List<Map<String, Object>> list = new ArrayList<>();42 43 for(int i = 1; i <= lastRowNum; i++ ){44 Map<String, Object> map = new HashMap<>();45 Row row = sheet.getRow(i);46 for(int j = 0; j < lastCellNum; j++){47 // 得到列名48 String key = titleRow.getCell(j).getStringCellValue();49 Cell cell = row.getCell(j);50 cell.setCellType(CellType.STRING);51 52 map.put(key, cell.getStringCellValue());53 }54 list.add(map);55 }56 workbook.close();57 return list;58 59 }60 }
前端:给出上传链接
1 <div class="layui-form-item">2 <label class="layui-form-label">选择文件</label>3 <div class="layui-input-block">4 <input type="file" name="mFile" id="no1" class="layui-input">5 </div>6 </div>7 <div class="layui-form-item">8 <input class="layui-btn" style="margin-left: 10%" id="btn1" type="submit" value="确认导入">9 </div>
后台controller层处理接收的excel文件
1 @RequestMapping("/staff/import.do") 2 @ResponseBody 3 public JsonBean importExcel(@RequestParam MultipartFile mFile){ 4 try { 5 String fileName = mFile.getOriginalFilename(); 6 // 获取上传文件的输入流 7 InputStream inputStream = mFile.getInputStream(); 8 // 调用工具类中方法,读取excel文件中数据 9 List<Map<String, Object>> sourceList = ImportExcel.readExcel(fileName, inputStream);10 11 // 将对象先转为json格式字符串,然后再转为List<SysUser> 对象12 ObjectMapper objMapper = new ObjectMapper();13 String infos = objMapper.writeValueAsString(sourceList);14 15 // json字符串转对象16 List<Staff> list = objMapper.readValue(infos, new TypeReference<List<Staff>>() {});17 18 // 批量添加19 staffService.addStaffBatch(list);20 21 return JsonUtils.createJsonBean(1, null);22 23 } catch (Exception e) {24 // TODO Auto-generated catch block25 e.printStackTrace();26 27 return JsonUtils.createJsonBean(0, e.getMessage());28 }29 30 }
注意:还要配置spring-bean.xml
<!-- 文件上传的解析器 id的值不能改-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的最大大小 ,单位字节 ,比如 1024 * 1024 = 1M-->
<property name="maxUploadSize" value="1048576"></property>
</bean>
【注意】excel每个列名要和数据库字段名一致!!
对于有date类型的数据,excel输入2019-12-12会变为日期格式数据,日期类型传到后台时会转成字符串,其格式会出错,就无法转换Date类型,
所以Excel表格一定要将时间相关数据用文本格式存储!!!
数据库对应实体类与时间相关属性要添加@DateTimeFormat(pattern="yyyy-MM-dd")注解