前几天做了一个Excel多个sheet页导入功能,有意思的东西习惯于一边开发,一边记录,供有需要的同学一个参考
1.JAR包准备
我这里用的maven,所以jar报直接引入了
1<dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi</artifactId> 4 <version>3.9</version> 5 </dependency> 6 <dependency> 7 <groupId>org.apache.poi</groupId> 8 <artifactId>poi-ooxml</artifactId> 9 <version>3.9</version> 10 </dependency>
2.核心代码
1public static List<ExcelSheetDto> getExeclStringArray(InputStream in, String fileName) throws Exception { 2 3 List<ExcelSheetDto> list = importExcel(in, 1, fileName);// 这里的1代表忽略的行数,比方说excel中有标题, 那么则从第2行开始读取数据 4 log.info("####导入excel页码####" + list.size()); 5 return list; 6 } 7 8 9 /** 10 * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行 11 * 12 * @param in 读取数据的源Excel 13 * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1 14 * @return 读出的Excel中数据的内容 15 * @throws FileNotFoundException 16 * @throws IOException 17 */ 18 19 public static List<ExcelSheetDto> importExcel(InputStream in, int ignoreRows, String fileName) throws FileNotFoundException, IOException { 20 List<ExcelSheetDto> list = new ArrayList<>(); 21 int rowSize = 0; 22 Workbook wb; 23 // 当excel是2003时,创建excel2003 24 if (isExcel2007(fileName)) { 25 wb = new XSSFWorkbook(in); 26 } else { 27 // 当excel是2007时,创建excel2007 28 wb = new HSSFWorkbook(in); 29 } 30 Cell cell = null; 31 String value; 32 for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { 33 ExcelSheetDto sheetDto = new ExcelSheetDto(); 34 List<String[]> result = new ArrayList<>(); 35 Sheet st = wb.getSheetAt(sheetIndex); 36 // 第一行为标题,不取 37 for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) { 38 Row row = st.getRow(rowIndex); 39 if (row == null) { 40 continue; 41 } 42 int tempRowSize = row.getLastCellNum() + 1; 43 if (tempRowSize > rowSize) { 44 rowSize = tempRowSize; 45 } 46 String[] values = new String[rowSize]; 47 Arrays.fill(values, ""); 48 boolean hasValue = false; 49 for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) { 50 value=getValue(row.getCell(columnIndex)); 51 if (columnIndex == 0 && value.trim().equals("")) { 52 continue; 53 } 54 values[columnIndex] = rightTrim(value); 55 hasValue = true; 56 } 57 if (hasValue) { 58 result.add(values); 59 } 60 } 61 String[][] returnArray = new String[result.size()][rowSize]; 62 for (int i = 0; i < returnArray.length; i++) { 63 returnArray[i] = result.get(i); 64 } 65 sheetDto.setSheetValue(returnArray); 66 list.add(sheetDto); 67 } 68 //in.close(); 69 return list; 70 71 } 72 73 /** 74 * 解决excel类型问题,获得数值 75 */ 76 public static String getValue(Cell cell) { 77 String value = ""; 78 if(null==cell){ 79 return value; 80 } 81 switch (cell.getCellType()) { 82 //数值型 83 case Cell.CELL_TYPE_NUMERIC: 84 if (HSSFDateUtil.isCellDateFormatted(cell)) { 85 //如果是date类型则 ,获取该cell的date值 86 Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()); 87 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 88 value = format.format(date); 89 }else {// 纯数字 90 BigDecimal big=new BigDecimal(cell.getNumericCellValue()); 91 value = big.toString(); 92 //解决1234.0 去掉后面的.0 93 if(null!=value&&!"".equals(value.trim())){ 94 String[] item = value.split("[.]"); 95 if(1<item.length&&"0".equals(item[1])){ 96 value=item[0]; 97 } 98 } 99 } 100 break; 101 //字符串类型 102 case Cell.CELL_TYPE_STRING: 103 value = cell.getStringCellValue().toString(); 104 break; 105 // 公式类型 106 case Cell.CELL_TYPE_FORMULA: 107 //读公式计算值 108 value = String.valueOf(cell.getNumericCellValue()); 109 if (value.equals("NaN")) { 110 // 如果获取的数据值为非法值,则转换为获取字符串 111 value = cell.getStringCellValue().toString(); 112 } 113 break; 114 // 布尔类型 115 case Cell.CELL_TYPE_BOOLEAN: 116 value = " "+ cell.getBooleanCellValue(); 117 break; 118 // 空值 119 case Cell.CELL_TYPE_BLANK: 120 value = ""; 121 break; 122 // 故障 123 case Cell.CELL_TYPE_ERROR: 124 value = ""; 125 break; 126 default: 127 value = cell.getStringCellValue().toString(); 128 } 129 if("null".endsWith(value.trim())){ 130 value=""; 131 } 132 return value; 133 } 134 135 136 137 public static boolean isExcel2007(String filePath) { 138 return filePath.matches("^.+\\.(?i)(xlsx)$"); 139 } 140 141 /** 142 * 去掉字符串右边的空格 143 * 144 * @param str 要处理的字符串 145 * @return 处理后的字符串 146 */ 147 148 public static String rightTrim(String str) { 149 150 if (str == null) { 151 return ""; 152 } 153 int length = str.length(); 154 for (int i = length - 1; i >= 0; i--) { 155 if (str.charAt(i) != 0x20) { 156 break; 157 } 158 length--; 159 } 160 return str.substring(0, length); 161 }
3.测试代码
1/** 2 * 测试导入 3 */ 4 @Test 5 public void testImport(){ 6 String savePath="C:\\Users\\WIN7\\Desktop\\mbbootstrap-angular\\Book1.xlsx"; 7 try { 8 File targetFile = new File(savePath); 9 InputStream input = new FileInputStream(targetFile); 10 List<ExcelSheetDto> listSheet=ExeclUtil.getExeclStringArray(input,"flight_inventory.xlsx"); 11 List<FlightInventory> flightInventory=new ArrayList<>(); 12 FlightInventory flightInventory1; 13 System.out.println(listSheet.get(0).getSheetValue().length); 14 for (int i = 0; i <listSheet.size(); i++) { //第一行循环多个sheet页 15 for (int j = 0; j<listSheet.get(i).getSheetValue().length; j++) { //循环多少行数据 16 flightInventory1=new FlightInventory(); 17 flightInventory1.setOriginCity(listSheet.get(i).getSheetValue()[j][3]); //代表第i个sheet页,第j行第3列数据 18 flightInventory.add(flightInventory1); 19 } 20 } 21 22 flightInventoryDao.batchInsertFlightInventory(flightInventory); //这里用的mabits批量插入, 不会的可以往下看,给出xml配置 23 System.out.println(flightInventory); 24 } catch (FileNotFoundException e) { 25 e.printStackTrace(); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 }
4.xml 配置
1<insert id="batchInsertFlightInventory" parameterType="java.util.List"> 2 insert into text(name, 3 age, 4 sex 5 ) 6 values 7 <foreach collection="list" index="index" item="item" separator="," open="(" close=")"> 8 #{item.name}, 9 #{item.age}, 10 #{item.sex} 11 12 </foreach> 13 </insert>
最后测试代码有删减,但整体逻辑和思路不变,如有问题,欢迎留言