POI Excel导入方法 ,及Date类型的获取方法

public R uploadFile(MultipartFile file){
		StringBuilder sb = new StringBuilder();
		try{
            //Equipment为我建的实体类
			List<Equipment> equipments = this.importBaseExcel(file);
			int trueNum = 1;
			if(equipments != null && equipments.size()>0){
				for(Equipment item:equipments){
					boolean save = addEquipment(item).isSuccess();
					trueNum++;
					if(save != true){
						sb.append(trueNum);
					}
				}
				if(StringUtils.isNotEmpty(sb)){
					return R.fail("出错行号"+sb+",上传失败");
				}else {
					return R.success("上传成功");
				}
			}else {
				return R.fail("未获取到导入数据,请检查excel");
			}

		}catch (Exception e){
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

private List<Equipment> importBaseExcel(MultipartFile file) throws Exception{

		Workbook workbook = null;
		//读取文件内容
		workbook = ExcelUtil.getUploadExcelWork(file);
		//获取工作表
		Sheet sheet = workbook.getSheetAt(0);
		//获取首行行号
		int firstRowNum = sheet.getFirstRowNum();
		//获取尾行行号
		int lastRowNum = sheet.getLastRowNum();
		List<Equipment> list = null;
		if(lastRowNum>0){
			list = new ArrayList<>();

			Equipment equipment = null;

			for(int i = 1; i <=lastRowNum;i++){
				Row row = sheet.getRow(i);
				equipment = new Equipment();
				//获取值
				String[] cellValue = getCellValue(row);
				//列序
				int j = 0;
				
                //此处一共十三项赋值,为了展示省略一部分
				//规格型号
				equipment.setDeviceSpec(cellValue[j++]);
				//出场时间
				equipment.setProductionTime(parse(cellValue[j++]));

				list.add(equipment);
			}
		}
		return list;
	}
    
    //excel中的日期类型单元格也和其它单元格一样,按照string类型来接收获取
	//获取行数据
	private String[] getCellValue(Row row){
		//列数
		int j = 13;
		String[] cellValue = new String[j];
		for(int i=0;i<j;i++){
			//获取单元格
            //两种不同的excel文件格式,xssf(.xlsx)和hssf(.xls)根据情况使用对应方法
			XSSFCell cell = (XSSFCell) row.getCell(i);
			//设置单元格类型
			cell.setCellType(CellType.STRING);
			//获取单元格数据
			cellValue[i] = cell.getStringCellValue();
		}
		return cellValue;
	}

	//字符串转date
	public Date parse(String date){
		try {
            //获取date类型的关键,使用poi的方法进行转换,将string转换成date
            //前面使用了xssf,这里用hssf也能成功?!?xssf好像没这个方法
			Date parseDate = HSSFDateUtil.getJavaDate(Double.valueOf(date));
			return parseDate;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值