java中excel文件上传

java文件上传

excel文件上传的两种方式

1.使用ExcelsUtils上传文件
2.把文件转换成流上传(支持多sheet)

代码实现
第一种方式
ExcelsUtils.ReadMultipartFile()可以直接读取文件 把文件转为byte数组 然后把字节数组转为json或者map,
第二种方式 把文件直接转为流(InputStream ins = new ByteArrayInputStream(file.getBytes())) 引入 new HSSFWorkbook(流)处理多sheet的情况

private List<Entity> readAndSetImport(MultipartFile file) {
		// 获得文件流
		InputStream ins = null;
		Workbook workbook = null;
		try {
			ins = new ByteArrayInputStream(file.getBytes());
		} catch (IOException e1) {
			log.error("读取流出错:{}", e1.getMessage());
			return null;
		}
		try {
			// 2007版本的excel,用.xlsx结尾
			workbook = new XSSFWorkbook(ins);
		} catch (Exception ex) {
			try {
				ins.reset();
				// 2003版本的excel,用.xls
				workbook = new HSSFWorkbook(ins);
			} catch (IOException e) {
				log.error("解析excel出错:{}", e.getMessage());
				return null;
			}
		}
		List<Entity> entitys= new ArrayList<>();
		try {
			// 获得第一个工作页
			Sheet sheet = workbook.getSheetAt(0);
			// 获得所有的字段
			Field[] fields = Entity.class.getDeclaredFields();
			Field field;
			List<String> fileList = new ArrayList<>(); // 文件里的中文字段名对应的对象字段名集合
			
			// 记录有多少行空的数据
			int count = 1;
			// 记录数据是从第几列开始记录的
			int begin = 0;
			for (int a = 0; a <= sheet.getLastRowNum(); a++) {
				Row row = sheet.getRow(a);
				if (row == null) {
					count++;
					continue;
				}
				boolean flag1 = false; // 标记该行有无数据
				for (Cell cell : row) {
					if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
						flag1 = true;
						break;
					}
				}
				if (flag1 == false) {
					count++;
					continue;
				}

				if (a < count){
					continue;
				}

				// 获得第一行不为空的数据为字段名
				if (a == count) {
					for (int b = 0; b < row.getLastCellNum(); b++) {
						Cell cell = row.getCell(b);
						if (fileList.isEmpty() && (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK)) {
							begin++;
						} else {
							for (int i = 0; i < fields.length; i++) {
								field = Entity.class.getDeclaredField(fields[i].getName());
								ValidationField annotation = field.getAnnotation(ValidationField.class);
								if (annotation != null) {
									String value = annotation.value();
									String excelField = cell.toString();
									if (excelField.equals(value)) {
										fileList.add(fields[i].getName());
										break;
									}
								}
							}
						}
					}
				} else  {
					Entity entity = new Entity();
					entity.setNumber(a + 1 + ""); // 设置行号
					for (int i = 0; i < fileList.size(); i++) {
						Cell cell = row.getCell(begin + i);
						if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
							continue;
						}
						field = Entity .class.getDeclaredField(fileList.get(i));
						field.setAccessible(true);
						// 读取excel表格设置对象字段值
						setFieldByExcel(entity, field, cell);
					}
					entitys.add(entity);
				}

			}

			
		} catch (Exception e) {
			log.error("解析excel 出错:{}",e.getMessage()); 
		}
		return entitys;
	}

对应实体类 (顺序不要随意更改)
@Data
public class Entity{

@ValidationField("行号")
private String number;

@ValidationField("姓名(*必填)")
private String userName;

@ValidationField("性别(*必填)")
private String gender;

..................................................................................
  private String errorDetails = "";
private List<String> errorFields = new ArrayList<>();
}

	/**
	 * 设置对象字段值(读取excel表)
	 *
	 * @param vo
	 *            对象
	 * @param field
	 *            字段
	 * @param cell
	 *            单元格
	 */
	private void setFieldByExcel(Entity entity, Field field, Cell cell) throws Exception {
		if (cell != null) {
			cell.setCellType(CellType.STRING);
		}
		if (field.getType() == String.class) {
			field.set(entity, cell.getStringCellValue());
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值