【Excel导入】将excel转化list对象数组的导入的排坑+简单实现

业务场景:其实在前面的文章里就有一些关于文件导入、读取的,但像OA业务的交互中,也不妨有许多表格导入的场景。

一、引入依赖

简单的一步,其实有很多问题
1.当我们引入如下依赖时,对应的一定是要相同,否则很容易出现问题
2.其次就是我们的pom文件中,引入的其他依赖会集成poi,导致版本不兼容,造成依赖冲突(idea里可以通过插件去掉)
3.再一个遇到的令人非常头疼的坑:Sheet sheet = workbook.getSheetAt(0);// 遍历Sheet 时候,Excel里面的sheet的识别会出现问题,可能会存在当删除掉一个sheet后,代码里只能getSheetAt(1) //取下一个索引 才能找到对应数据,不妨去新建一个Excel,再来执行。

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.16</version>
        </dependency>

二、创建工具类


public class POIUtil {
    
    

	private static final String EXCEL_XLS = "xls";
	private static final String EXCEL_XLSX = "xlsx";
	private static final String EXCEL_XLSM = "xlsm";

	/**
	 * 判断Excel的版本,获取Workbook
	 * 
	 * @param in
	 * @param
	 * @return
	 * @throws IOException
	 */
	public static Workbook getWorkbok(InputStream in, File file) {
    
    
		Workbook wb = null;
		if (file.getName().endsWith(EXCEL_XLS)) {
    
     // Excel 2003
			try {
    
    
				wb = new HSSFWorkbook(in);
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		} else if (file.getName().endsWith(EXCEL_XLSX) || file.getName().endsWith(EXCEL_XLSM)) {
    
     // Excel
																									// 2007/2010
			try {
    
    
				wb = new XSSFWorkbook(in);
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}

		}
		return wb;
	}

	/**
	 * 判断文件是否是excel
	 * 
	 * @throws Exception
	 */
	public static void checkExcelVaild(File file) throws Exception {
    
    
		if (!file.exists()) {
    
    
			throw new Exception("文件不存在");
		}
		if (!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)
				|| file.getName().endsWith(EXCEL_XLSM)))) {
    
    
			throw new Exception("文件不是Excel");
		}
	}

	/**
	 * 读取Excel测试,兼容 Excel 2003/2007/2010
	 * 
	 * @throws Exception
	 */
	public static List<ArrayList<String>> readData(MultipartFile file) throws Exception {
    
    
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		List<ArrayList<String>> excelData = new ArrayList<>();
		ArrayList<String> rowData = new ArrayList<>();
		try {
    
    
			File f = null;
			// 同时支持Excel 2003、2007
			if (file.equals("") || file.getSize() <= 0) {
    
    
				file = null;
			} else {
    
    
				f = new File(file.getOriginalFilename());
			}
			log.info("readData************************************11111111*******");
			// checkExcelVaild(f);
			InputStream is = file.getInputStream();
			Workbook workbook = getWorkbok(is, f);

			int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量
			/**
			 * 设置当前excel中sheet的下标:0开始
			 */
			Sheet sheet = workbook.getSheetAt(0); // 遍历第一个Sheet
			// Sheet sheet = workbook.getSheetAt(2); // 遍历第三个Sheet

			// 获取总行数
			// System.out.println(sheet.getLastRowNum());

			// 为跳过第一行目录设置count
			int count = 0;
			for (Row row : sheet) {
    
    
//				log.info("sheet**********************************************" );
				rowData = new ArrayList<>();
				try {
    
    
					// 跳过第一目录
					if (count < 1) {
    
    
						count++;
						continue;
					}

					// 如果当前行没有数据,跳出循环
					if (row.getCell(1) == null || row.getCell(1).toString().equals("")) {
    
    
						return excelData;
					}
					// 获取总列数(空格的不计算)
					// int columnTotalNum = row.getPhysicalNumberOfCells();
					// System.out.println("总列数:" + columnTotalNum);

					// System.out.println("最大列数:" + row.getLastCellNum());

					// for循环的,不扫描空格的列
					// for (Cell cell : row) {
    
    
					// System.out.println(cell);
					// }
					int end = row.getLastCellNum();
					for (int i = 0; i < end; i++) {
    
    

						Cell cell = row.getCell(i);
						if (cell == null) {
    
    
							// System.out.print("null" + "\t");
							continue;
						}
						// int cellTypeEnum = cell.getCellType();
						String obj = getValue(cell);
						if (obj.equals("#N/A")) {
    
    
							return excelData;
						}
						rowData.add(obj);
					}
					excelData.add(rowData);
					is.close();
				} catch (Exception e) {
    
    
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return excelData;
	}

	/**
	 * 读取Excel测试,兼容 Excel 2003/2007/2010
	 * 
	 * @throws Exception
	 */
	public static List<ArrayList<String>> readData(String fileName, String fileContent) throws Exception {
    
    

		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		List<ArrayList<String>> excelData = new ArrayList<>();
		ArrayList<String> rowData = new ArrayList<>();
		try {
    
    
			File f = null;
			// 同时支持Excel 2003、2007
			f = new File(fileName);
			// checkExcelVaild(f);
			byte[] decryptBASE64 = BASE64.decryptBASE64(fileContent);
			InputStream in = new ByteArrayInputStream(decryptBASE64);
			Workbook workbook = getWorkbok(in, f);

			int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量
			/**
			 * 设置当前excel中sheet的下标:0开始
			 */
			Sheet sheet = workbook.getSheetAt(0); // 遍历第一个Sheet
			// Sheet sheet = workbook.getSheetAt(2); // 遍历第三个Sheet

			// 获取总行数
			// System.out.println(sheet.getLastRowNum());

			// 为跳过第一行目录设置count
			int count = 0;
			int end = 0;
			for (Row row : sheet) {
    
    
				rowData = new ArrayList<>();
				try {
    
    
					// 跳过第一目录
					if (count == 0) {
    
    
						end = row.getLastCellNum();
						count++;
						// continue;
					}

					// 如果当前行没有数据,跳出循环
					if (row.getCell(1) == null || row.getCell(1).toString().equals("")) {
    
    
						return excelData;
					}
					// 获取总列数(空格的不计算)
					// int columnTotalNum = row.getPhysicalNumberOfCells();
					// System.out.println("总列数:" + columnTotalNum);

					// System.out.println("最大列数:" + row.getLastCellNum());

					// for循环的,不扫描空格的列
					// for (Cell cell : row) {
    
    
					// System.out.println(cell);
					// }
					for (int i = 0; i < end; i++) {
    
    

						Cell cell = row.getCell(i);
						String obj = "";
						if (cell == null) {
    
    
							// System.out.print("null" + "\t");
							rowData.add(obj);
							continue;
						}
						// int cellTypeEnum = cell.getCellType();
						obj = getValue(cell);
						// System.out.print(obj+"\t");
						if (obj.equals("#N/A")) {
    
    
							return excelData;
						}
						rowData.add(obj);
					}
					excelData.add(rowData);
					// System.out.println("\n");
					in.close();
				} catch (Exception e) {
    
    
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return excelData;
	}

	public static byte[] getFileToByte(File file) {
    
    
		byte[] by = new byte[(int) file.length()];
		try {
    
    
			InputStream is = new FileInputStream(file);
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
			byte[] bb = new byte[2048];
			int ch;
			ch = is.read(bb);
			while (ch != -1) {
    
    
				bytestream.write(bb, 0, ch);
				ch = is.read(bb);
			}
			by = bytestream.toByteArray();
			is.close();
			bytestream.close();
		} catch (Exception e) {
    
    
			log.error(e);
		}
		return by;
	}

	private static String getValue(Cell cell) {
    
    
		String obj = "";
		switch (cell.getCellType()) {
    
    
		case Cell.CELL_TYPE_BOOLEAN:
			obj = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_ERROR:
			obj = String.valueOf(cell.getErrorCellValue());
			break;
		case Cell.CELL_TYPE_NUMERIC:
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			obj = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_STRING:
			obj = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_FORMULA:
			try {
    
    
				obj = cell.getStringCellValue();
			} catch (IllegalStateException e) {
    
    
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				obj = cell.getStringCellValue();
			}
		default:
			break;
		}
		return obj.trim();
	}
}

三、调用工具类


    public List importExcl(MultipartFile file) {
    
    
        ArrayList<CampUserHouse> list = new ArrayList<>();
        List<ArrayList<String>> lists = null;
        try {
    
    
            lists = POIUtil.readData(file);
            for (int i = 0; i < lists.size(); i++) {
    
    
                ArrayList<String> arrayList = lists.get(i);
//                 todo 直接用相应的数据结构去遍历接收
//                Entity entity = new Entity();
//                entity.setOne(arrayList.get(0));
//                list.add(entity);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return list;
    }


猜你喜欢

转载自blog.csdn.net/qq_48424581/article/details/130620939