【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;
    }


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 实现 Excel 导入数据可以使用对象映射技术,将 Excel 中的数据映射到 Java 对象中。下面是一些实现步骤: 1. 导入相关的 jar 包:使用 Apache POI 库来读取 Excel 文件,使用 Apache Commons BeanUtils 库来进行对象映射。 2. 创建 Java 实体类:创建一个 Java 类来映射 Excel 中的数据,属性名与 Excel 中的列名对应。 3. 读取 Excel 文件:使用 POI 库来读取 Excel 文件,获取到每一行的数据。 4. 对象映射:使用 BeanUtils 库将 Excel 中的数据映射到 Java 实体类中。 5. 将 Java 对象保存到数据库:使用 JDBC 或者 ORM 框架将 Java 对象保存到数据库中。 下面是一个简单的示例代码: ```java // 创建 Java 实体类 public class User { private String name; private int age; private String email; // 省略 getter 和 setter 方法 } // 读取 Excel 文件 File file = new File("data.xlsx"); Workbook workbook = WorkbookFactory.create(file); Sheet sheet = workbook.getSheetAt(0); List<User> userList = new ArrayList<>(); for (Row row : sheet) { User user = new User(); user.setName(row.getCell(0).getStringCellValue()); user.setAge((int) row.getCell(1).getNumericCellValue()); user.setEmail(row.getCell(2).getStringCellValue()); userList.add(user); } // 对象映射 List<UserEntity> userEntityList = new ArrayList<>(); for (User user : userList) { UserEntity userEntity = new UserEntity(); BeanUtils.copyProperties(userEntity, user); userEntityList.add(userEntity); } // 将 Java 对象保存到数据库 for (UserEntity userEntity : userEntityList) { userDao.save(userEntity); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值