使用POI读取Excel转成任意bean并校验数据且导入MySQL

前言

这个功能前一阵在工作中也是遇到过,我用的POI版本也是比较低的,在这里我也只是想简单的记录一下思路及方法,为了方便日后查看……

maven依赖

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

定义bean

一个sheet页对应一个bean,方便读取Excel数据做转换(我是五个sheet页,建议bean的成员变量类型都选择String,防止报错,需要其它类型后期还可以再转换)
在这里插入图片描述

/**
 * 基本信息
 * @author fuzhongxu
 *
 */
public class BasicInformation {

	private String CaseTitle;
	
	private String CaseType;
	
	private String CauseOfAction;//案由
	
	private String HearingProcedure;//审理程序
	
	private String TrialInstitutions;//审理机构
	
	private String TrialInstitutionsCaseNo;//审理机构案号
	
	private String TheCaseNumber;//所内案号
	
	private String bdObject;//标的
	
	private String CounselFee;//律师费数额
	
	private String CounselFeePaymentAgreement;//律师费付款约定
	
	private String Remarks;//备注

	构造方法:略……
	set/get:略……
	
}
/**
 * 当事人-个人信息
 * @author fuzhongxu
 *
 */
public class PersonalInformationOfParties {

	private String CaseTitle;
	
	private String Attribute;//属性
	
	private String EntrustingParty;//标为委托方
	
	private String PartiesType;//当事人类型(个人/单位)
	
	private String PartiesName;//当事人姓名
	
	private String PartiesSex;//当事人性别
	
	private String InsertCrm;//新建至主体管理系统
	
	private String CertificateType;//证件类型
	
	private String IDNumber;//证件号码
	
	private Date DateOfBirth;//出生日期
	
	private String Nation;//民族
	
	private String Address;//住址
	
	private String contactWay;//联系方式
	
	private String PartiesRemarks;//当事人备注

	构造方法:略……
	set/get:略……
	
}
/**
 * 当事人单位信息
 * @author fuzhongxu
 *
 */
public class PartyUnitInformation {

	private String CaseTitle;
	
	private String Attribute;//属性
	
	private String EntrustingParty;//标为委托方
	
	private String PartiesType;//当事人类型(个人/单位)
	
	private String PartiesName;//当事人姓名
	
	private String InsertCrm;//新建至主体管理系统
	
	private String Domicile;//住所地
	
	private String LegalRepresentative;//法定代表人
	
	private String UnifiedSocialCreditCode;//统一社会信用代码
	
	private String Remarks;//备注
	
	构造方法:略……
	set/get:略……
	
}
/**
 * 审理人员信息
 * @author fuzhongxu
 *
 */
public class InformationOfAdjudicators {

	private String CaseTitle;
	
	private String AdjudicatorsName;//审理人员名称
	
	private String contactWay;//联系方式
	
	private String OtherInformation;//其他信息
	
	构造方法:略……
	set/get:略……
	
}
/**
 * 辅助人员信息
 * @author fuzhongxu
 *
 */
public class SupportStaffInformation {

	private String CaseTitle;
	
	private String StaffPersonnelName;//辅助人员姓名
	
	private String contactWay;//联系方式
	
	private String OtherInformation;//其他信息
	
	构造方法:略……
	set/get:略……
	
}

核心代码(任意bean转换)

	/**
	 * 实现任意类的封装
	 * @param sheet
	 * @param workBook
	 * @param aimClass
	 * @return
	 */
	public <T> List<T> parseFromExcel(Sheet sheet, int firstIndex, Class<T> aimClass) {
		List<T> result = new ArrayList<T>();
		//String format = null;
		Date cellValue = null;
		String cellContent = null;
		try {
            //对excel文档的第一页,即sheet1进行操作
			int lastRaw = sheet.getPhysicalNumberOfRows();
			for (int i = firstIndex; i <= lastRaw; i++) {
                //第i行
				Row row = sheet.getRow(i);
				if(row == null){
					continue;
				}
				T parseObject = aimClass.newInstance();
				Field[] fields = aimClass.getDeclaredFields();
				for (int j = 0; j < fields.length; j++) {
					Field field = fields[j];
					field.setAccessible(true);
					Class<?> type = field.getType();
                    //第j列
					Cell cell = row.getCell(j);
					if(type.equals(Date.class)){
						if(org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)){
							cellValue = cell.getDateCellValue();
							/*SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
							format = ft.format(cellValue);*/
						}
					}
					if (cell == null)
						continue;
                    //很重要的一行代码,如果不加,像12345这样的数字是不会给你转成String的,只会给你转成double,而且会导致cell.getStringCellValue()报错
					cell.setCellType(Cell.CELL_TYPE_STRING);
					cellContent = cell.getStringCellValue();
					cellContent = "".equals(cellContent) ? "0" : cellContent;
					if (type.equals(String.class)) {
						field.set(parseObject, cellContent);
					} else if (type.equals(char.class) || type.equals(Character.class)) {
						field.set(parseObject, cellContent.charAt(0));
					} else if (type.equals(int.class) || type.equals(Integer.class)) {
						field.set(parseObject, Integer.parseInt(cellContent));
					} else if (type.equals(long.class) || type.equals(Long.class)) {
						field.set(parseObject, Long.parseLong(cellContent));
					} else if (type.equals(float.class) || type.equals(Float.class)) {
						field.set(parseObject, Float.parseFloat(cellContent));
					} else if (type.equals(double.class) || type.equals(Double.class)) {
						//field.set(parseObject, Double.parseDouble(cellContent));
						field.set(parseObject, cellContent);//根据实际情况自行选择要double还是string(我这里虽然要的是string,但后期还是转成double了)
					} else if (type.equals(short.class) || type.equals(Short.class)) {
						field.set(parseObject, Short.parseShort(cellContent));
					} else if (type.equals(byte.class) || type.equals(Byte.class)) {
						field.set(parseObject, Byte.parseByte(cellContent));
					} else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
						field.set(parseObject, Boolean.parseBoolean(cellContent));
					} else if(type.equals(Date.class)){
						field.set(parseObject, cellValue);
					}
				}
				result.add(parseObject);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("An error occured when parsing object from Excel. at " + this.getClass());
		}
		return result;
	}

校验数据

这里就简单说一下,刚才需要转换成double类型的数据是如何转换校验的

		Sheet sheet1 = workBook.getSheet("基本信息");
		private static final Pattern PATTERN = Pattern.compile("^(([1-9]{1}\\d{0,11})|(0{1}))(\\.\\d{1,2})?$");
		//parseFromExcel方法参数解读:(1)得到的sheet页(2)从第几行开始读数据(3)当前sheet页要转成对应的bean
		List<BasicInformation> basicInformations = parseFromExcel(sheet1, 3, BasicInformation.class);
		
		for(int i = 0; i < basicInformations.size();i++){
			if(StringUtils.isNotBlank(basicInformations.get(i).getBdObject())){
				try {
					Double bdObject = Double.parseDouble(basicInformations.get(i).getBdObject());
					if(bdObject instanceof Double == true){
						BigDecimal bd = new BigDecimal(bdObject.toString());
						BigDecimal db = new BigDecimal("999999999999.99");
						//最大值是999999999999.99
						if(1 == bd.compareTo(db)){
							map = new HashMap<String, Object>();
							map.put("particulars", "标的");
							map.put("type", 8);
							resultList1.add(map);
						//小数点后最多保留两位
						}else if(StringUtils.isNotBlank(bd.toPlainString().toString()) && !PATTERN.matcher(bd.toPlainString().toString()).matches()){
							map = new HashMap<String, Object>();
							map.put("particulars", "标的");
							map.put("type", 7);
							resultList1.add(map);
						}
					}
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					map = new HashMap<String, Object>();
					map.put("particulars", "标的");
					map.put("type", 2);
					resultList1.add(map);
				}
			}
		}
到现在为止已经差不多了,剩下的就是把读出来的list数据集合,添加到数据库中……

OK,今天的分享记录到此为止,如若发现不对的地方我再改,over~❤❤❤

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/** * 此代码是完excel导入电话号码,将正确的电话号码保存到set集合中,因为set集合对于重复的值会覆盖,所以达到了去重复的值的用例,并累计了不正确的电话号码的个数,对电话号码进行了验证有效性。所需要的 dom4j-1.6.1.jar;geronimo-stax-api_1.0_spec-1.0.jar;poi-3.7-20101029.jar;poi-ooxml-3.7-20101029.jar;poi-ooxml-schemas-3.7-20101029.jar;xmlbeans-2.3.0.jar; */ public static void main(String[] args) { Long errorMobileTotal=0L; // 保存正确的电话号码 Set<String> mobileSet = new HashSet<String>(); try { XSSFWorkbook wb = new XSSFWorkbook("E:/workbook1.xlsx"); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row = null; XSSFCell cell = null; String mobileStr=""; for (int i = 0; i <= sheet.getLastRowNum(); i++) { row = sheet.getRow(i); //System.out.print("第" + i + "行共" + row.getLastCellNum() +"列: "); for (int y = 0; y < row.getLastCellNum(); y++) { cell = row.getCell(y); // 设置字段为字符类型 cell.setCellType(XSSFCell.CELL_TYPE_STRING); // 判断储存格的格式 if (cell != null) { // 取得单元格的值 mobileStr = cell.getStringCellValue(); // 对手机号码进行验证身份正确 if(isMobileNO(mobileStr)) { // 保存正确的手机号码 mobileSet.add(mobileStr); System.out.println("号码"+mobileStr+"正确"); } else { // 累计不正确的电话号码的个数 errorMobileTotal++; System.out.println("不正确的电话号码个数:"+errorMobileTotal); System.out.println("号码"+mobileStr+"不正确"); } } // end (cell != null) }// end 遍历当前行 } // end 遍历当前工作单元sheet System.out.println("总共的行数:"+ (Long.valueOf(sheet.getLastRowNum())+1)); } catch (Exception e) { e.printStackTrace(); } // 因为要去除重复的所以可能有存在替换的字符 System.out.println("不正确的电话号码个数:"+errorMobileTotal); System.out.println("正确的电话号码个数:" + mobileSet.size()); } public static boolean isMobileNO(String mobiles){ Pattern p = Pattern.compile("^(\\+86)*0*((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值