excel转换成实体
package com.cinc.ecmp.utils; import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import com.cinc.ecmp.annotation.ExcelField;
import com.cinc.ecmp.enums.BackResultEnum;
import com.cinc.ecmp.exception.BasException; import lombok.extern.slf4j.Slf4j; /**
* @author j
* 操作方式:
* 根据Excel格式编写vo,vo编写方式参照com.cinc.ecmp.demo.vo.ExcelMaterialVo
*/
@Slf4j
public class ExcelParseUtils { public static <T> List<T> parse(MultipartFile file,Class<T> clazz){
Workbook hwb=null;
InputStream in = null;
try{
if(null == file){
throw new BasException(BackResultEnum.DATAPARSEERR);
}
in = file.getInputStream();
hwb=WorkbookFactory.create(in);
Sheet sheet=hwb.getSheetAt(0);
if(sheet==null) {
return null;
}
List<T> excelVoList=new ArrayList<T>();
Field[] fields=clazz.getDeclaredFields();
for(int i=sheet.getFirstRowNum()+1;i<sheet.getPhysicalNumberOfRows();i++) {
Row row = sheet.getRow(i);
if(null==row.getCell(1)||row.getCell(1).getCellType()==CellType.BLANK) {
break;//如果这一行的第一列为空,则终止解析
}
T object = clazz.newInstance();
for(Field field:fields) {
//获取该字段的列号
ExcelField excelField=field.getAnnotation(ExcelField.class);
if(null == excelField) {
continue;
}
int index = excelField.index();
String value="";
Cell cell = row.getCell(index);
if(null == cell) {
continue;
}
CellType cellType = cell.getCellType();
switch(cellType) {
case STRING:
value = String.valueOf(cell.getRichStringCellValue());
break;
case FORMULA:
try {
value = String.valueOf(cell.getNumericCellValue());
}catch (Exception e) {
value = String.valueOf(cell.getRichStringCellValue());
}
break;
case NUMERIC:
if(HSSFDateUtil.isCellDateFormatted(cell)) {
Date date=HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
value=DateUtil.getDateTimeStringToDb(date);
}else {
DecimalFormat df = new DecimalFormat();
value = df.format(cell.getNumericCellValue());
}
break;
case BLANK:
break;
default:
throw new BasException(BackResultEnum.DATAPARSEERR);
}
//非空判断
if(excelField.required()&&StringUtils.isEmpty(value)) {
log.error("【{}不能为空】",excelField.desc());
throw new BasException(BackResultEnum.DATAPARSEERR);
}
//数据合法性判断
String[] dataScopes=excelField.inList();
if(!CollectionUtils.isEmpty(Arrays.asList(dataScopes))&&!Arrays.asList(dataScopes).contains(value)) {
log.error("【{}不合法】",excelField.desc());
throw new BasException(BackResultEnum.DATAPARSEERR);
}
//字段类型设置
Class<?> typeClass=field.getType();
Method method = clazz.getMethod("set" + Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1), typeClass);
//将字段值设置到对象中
try {
if(typeClass==Integer.class) {
method.invoke(object, value.indexOf(".")>0?Integer.parseInt(value.substring(0, value.indexOf("."))):Integer.parseInt(value));
}else if(typeClass==BigDecimal.class) {
method.invoke(object, new BigDecimal(value.indexOf(",")>0?value.replaceAll(",", ""):value));
}else {
method.invoke(object, value.indexOf(",")>0?value.replaceAll(",", ""):value);
}
}catch (Exception e) {
log.error("【{}设置错误】",excelField.desc(),e);
throw new BasException(BackResultEnum.DATAPARSEERR);
}
}
if(excelVoList.contains(object)) {
log.error("【导入失败,数据存在重复】");
throw new BasException(BackResultEnum.DATAREPEATERR);
}
excelVoList.add(object);
}
return excelVoList;
}catch (Exception e) {
log.error("【文件上传失败】",e);
throw new BasException(BackResultEnum.FILEUPLOADERR);
}finally {
if(null != hwb){
try {
hwb.close();
} catch (IOException e) {
log.error("【文件流关闭失败】",e);
}
}
if(null != in){
try {
in.close();
} catch (IOException e) {
log.error("【文件流关闭失败】",e);
}
}
}
}
}
vo实体类的编写:
package com.cinc.ecmp.demo.vo; import java.math.BigDecimal; import com.cinc.ecmp.annotation.ExcelField; import lombok.Data; /**
* @author
* @time 2019年7月2日 下午7:59:26
*/
@Data
public class ExcelMaterialVo { @ExcelField(index=0,required=true,desc="材料名称")
private String name; @ExcelField(index=1,required=true,desc="价格")
private BigDecimal price; @ExcelField(index=2,required=true,desc="采购数量")
private Integer count;
}
注解的编写:
package com.cinc.ecmp.annotation; import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target; @Retention(RUNTIME)
@Target(FIELD)
@Inherited
public @interface ExcelField { /**
* Excel表格列顺序,起始为0
* @return
*/
int index(); /***
* 数据范围
* @return
*/
String[] inList() default {}; /***
* 正则
* @return
*/
String pattern() default ""; /***
* 字段描述
* @return
*/
String desc() default ""; /**
* 是否是必须的
*
* @return
*/
boolean required() default false;
}
@Override
public List<ExcelMaterialVo> upload(MultipartFile file){
List<ExcelMaterialVo> excelMaterialVoList=ExcelParseUtils.parse(file, ExcelMaterialVo.class);
return excelMaterialVoList;
}
excel转换成实体的更多相关文章
- Epplus下的一个将Excel转换成List的范型帮助类
因为前一段时间公司做项目的时候,用到了Excel导入和导出,然后自己找了个插件Epplus进行操作,自己将当时的一些代码抽离出来写了一个帮助类. 因为帮助类是在Epplus基础之上写的,项目需要引用E ...
- C# 将DataTable数据源转换成实体类
using System; using System.Collections.Generic; using System.Data; using System.Reflection; /// < ...
- 字符串js编码转换成实体html编码的方法(防范XSS攻击)
js代码在html页面中转换成实体html编码的方法一: <!DOCTYPE html><html> <head> <title>js代码转换成实 ...
- C# DataTable转换成实体列表 与 实体列表转换成DataTable
/// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...
- sql hibernate查询转换成实体或对应的VO Transformers
sql查询转换成实体或对应的VO Transformers //addScalar("id") 默认查询出来的id是全部大写的(sql起别名也无效,所以使用.addScalar(& ...
- hibernate查询部分字段转换成实体bean
//hibernate查询部分字段转换成实体bean /** * 查询线路信息 */ @Override public List<Line> getSimpleLineListByTj(M ...
- How to cast List<Object> to List<MyClass> Object集合转换成实体集合
List<Object> list = getList(); return (List<Customer>) list; Compiler says: cannot cast ...
- Table转换成实体、Table转换成实体集合(可转换成对象和值类型)
/// <summary> /// Table转换成实体 /// </summary> /// <typeparam name="T">< ...
- DataTable转换成实体
public static class DataTableToEntity { /// <summary> /// 将DataTable数据源转换成实体类 /// </summary ...
随机推荐
- 【风马一族_php】PHP运算
运算 算术运算符 <?php //加法 $num1 = 10; $num2 = 43; echo $num1 + $num2; echo " "; var_dump($num ...
- js赋值符号“=”的小例子
var obj1={x:5}; var obj2=obj1; obj1.a=obj1={x:6}; console.log(obj1.a); console.log(obj2.a); 为什么obj1. ...
- [React Native]去掉WebStorm中黄色警告
用WebStorm开发RN难免会碰到一大堆黄色警告.就像下面这样. 其实这个错误并不会影响开发,但是作为一个上升处女座的,我很难忍.于是各种想办法. 上网查了半天发现这篇文章 http://blog. ...
- NDK(1)简介
AndroidNDK Android NDK 是在SDK前面又加上了“原生”二字,即Native Development Kit,因此又被Google称为“NDK”. Android程序运行在Dalv ...
- DOTA轮播
原文:DOTA轮播 本人录制技术视频地址:https://edu.csdn.net/lecturer/1899 欢迎观看. 这一节介绍一下Dota轮播,先看看最终效果图. 一.HTML代码分析: &l ...
- 字符串分割+二维数组 Day15练习
package com.sxt.arrays.test; import java.util.Arrays; /* 1,2,3,4!5,6,7!8,9!12,456,90!32 * 将此字符串以叹号为分 ...
- Python数据集变量及相关含义
- Round #590 (Div. 3)
拿DIV找快乐... 当场过了A-B1-B2-C 写D差5分钟写的是正解...留坑补FG A. Equalize Prices Again 直接判断sum%n==0?sum/n:sum/n+1 B1, ...
- kubernetes API 访问控制在阿里云容器服务(ACK)上的实践
提起K8s API的访问控制,很多同学应该都会想到RBAC,这是K8s用来做权限控制的方法,但是K8s对API的访问控制却不止于此,今天我们就来简单介绍下K8s的访问控制以及ACK如何利用这套方法提供 ...
- GitHub 上 10 款免费开源 Windows 工具
GitHub 上 10 款免费开源 Windows 工具 GitHub 是如今所有开源事物的中央仓库, 这个网站最近发布了一个叫做<2016 Octoverse 状态报告>,详细列出了从 ...