工具类
@Component
public class ExcelUtils<E> {
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
/**
*
* @param tClass 文件要转化的实体类的class
* @param file 文件数据
* @param column columnOption(实体类属性按照excel顺序排列的json字符串)
* 例如:[{"type":"input","label":"名字","prop":"name"},{"type":"input","label":"性别","prop":"age"},{"type":"input","label":"住址","prop":"address"},]
* @return 实体类的list
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IOException
* @throws NoSuchFieldException
* @throws ParseException
*/
public List<E> excelToEntityList(Class<E> tClass, MultipartFile file, String column) throws InstantiationException, IllegalAccessException, IOException, NoSuchFieldException, ParseException {
List<RequestVo> fields = stringToRequestVo(column);
ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
List<E> objects = new ArrayList<>();
int lastRowNum = reader.getSheet().getLastRowNum()+1;
for (int i = 1; i < lastRowNum; i++) {
List<Object> values = reader.readRow(i);
if (values.size()==0){
continue;
}
E instance = tClass.newInstance();
while (values.size() < fields.size()) {
values.add("");
}
for (int j = 0; j < fields.size(); j++) {
RequestVo requestVo = fields.get(j);
String value = values.get(j) == null ? "" : values.get(j).toString();
Field declaredField = tClass.getDeclaredField(requestVo.getProp());
declaredField.setAccessible(true);
if (StrUtil.isNotEmpty(value)) {
if (declaredField.getType().getName().equals("java.util.Date")) {
declaredField.set(instance, simpleDateFormat.parse(value));
} else if (declaredField.getType().getName().equals("java.lang.Integer")) {
declaredField.set(instance, Integer.valueOf(value));
} else if (declaredField.getType().getName().equals("java.lang.Double")) {
declaredField.set(instance, Double.valueOf(value));
} else if (declaredField.getType().getName().equals("java.lang.String")) {
declaredField.set(instance, value);
}
}
}
objects.add(instance);
}
return objects;
}
private List<RequestVo> stringToRequestVo(String column) {
List<JSONObject> columns = JSON.parseObject(column, ArrayList.class);
return columns.stream().map(v -> {
RequestVo requestVo = new RequestVo();
requestVo.setProp((String) v.get("prop"));
String label = (String) v.get("label");
try {
requestVo.setLabel(new String(label.getBytes("iso-8859-1"), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
requestVo.setType((String) v.get("type"));
return requestVo;
}).collect(Collectors.toList());
}
}
根据例子对应的excel,字段的前后要一一对应
RequestVo.java
@Data
public class RequestVo {
private String type;
private String label;
private String prop;
}
注意:columnOption中的prop对应的是实体类中的属性名称,columnOption可以直接从前端的tableOption中搞到,avue的tableOption