将Excel文件一键解析为list对象集合

news/2024/10/20 20:41:30/

调用代码:

@Override
public List<VirtualSettleAccountExcelData> importExcel(String accountNo, MultipartFile file) {List<VirtualSettleAccountExcelData> virtualSettleAccountExcelDataList=null;try {String name = file.getOriginalFilename();if (!name.contains(".xls") && !name.contains(".xlsx")) {throw new Exception("文件格式不正确");}//导入的字段以及对应的值Map<String, String> titleMap = new HashMap();titleMap.put("订单编号", "virtualAccountAppId");titleMap.put("新网客户虚户", "virtualAccountNo");//要校验必填的数据Map<String, String> checkMap = new HashMap();checkMap.put("virtualAccountAppId","订单编号");checkMap.put("virtualAccountNo","新网客户虚户");virtualSettleAccountExcelDataList= ExcelUtil.excelToDataList(file.getInputStream(),name,VirtualSettleAccountExcelData.class,titleMap,checkMap);} catch (Exception ex) {logger.warn("解析虚户数据 error" ,ex.getMessage(), ex);}return virtualSettleAccountExcelDataList;
}

ExcelUtil封装类代码:

package geex.fin.acc.utils;import com.google.common.collect.Lists;
import jxl.read.biff.BiffException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;public class ExcelUtil {private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);private final static String xls = "xls";private final static String xlsx = "xlsx";/**** @param row          excel中的某一行* @param list         excel一行数据对应的MerchantImportReq属性值顺序存放在list中* @param firstCellNum 开始列* @param lastCellNum  结束列* @return* @throws Exception*/private static <T> T excelTOData(Row row, List<String> list, Integer firstCellNum, Integer lastCellNum,T t) throws Exception {Class clazz = t.getClass();int i = 0;for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {if(i<list.size()) {Cell cell = row.getCell(cellNum);Field field = clazz.getDeclaredField(list.get(i++));field.setAccessible(true);String cellValue = getCellValue(cell,cellNum);field.set(t, cellValue);}}return t;}/*** 获取excel单元格的值** @param cell 单元格* @return value值* @throws Exception*/public static String getCellValue(Cell cell,int cellNum) throws Exception {String cellValue = null;if (cell == null) {return cellValue;}//把数字当成String来读,避免出现1读成1.0的情况if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {if (cell.getCellStyle().getDataFormatString().indexOf("%") != -1) {Double numValue=cell.getNumericCellValue()*100;String dValue = String.format("%.2f", numValue);cellValue = dValue+ "%";cell.setCellValue(cellValue);//此处因为我要将错误数据导出,所以把值写回到列中。} else if(!HSSFDateUtil.isCellDateFormatted(cell)){cell.setCellType(Cell.CELL_TYPE_STRING);}else {cellValue = cell.toString();}}if(cell.getCellType()==Cell.CELL_TYPE_FORMULA){int cellNu=cellNum+1;throw new Exception("第"+cellNu+"列格式不正确,不支持公式数据读取");}//判断数据的类型switch (cell.getCellType()) {case Cell.CELL_TYPE_NUMERIC: //数字if (HSSFDateUtil.isCellDateFormatted(cell)){Date date = cell.getDateCellValue();//格式转换SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String format = sdf.format(date);System.out.println(format);return format;}cellValue = String.valueOf(cell.getNumericCellValue());break;case Cell.CELL_TYPE_STRING: //字符串cellValue = String.valueOf(cell.getStringCellValue());break;case Cell.CELL_TYPE_BOOLEAN: //BooleancellValue = String.valueOf(cell.getBooleanCellValue());break;case Cell.CELL_TYPE_FORMULA: //公式cellValue = String.valueOf(cell.getCellFormula());break;case Cell.CELL_TYPE_BLANK: //空值break;default:throw new Exception("存在非法格式的单元格"); //其他类型报错}return cellValue;}public static String getCellValue(Cell cell) throws Exception {String cellValue = null;if (cell == null) {return cellValue;}//把数字当成String来读,避免出现1读成1.0的情况if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {cell.setCellType(Cell.CELL_TYPE_STRING);}//判断数据的类型switch (cell.getCellType()) {case Cell.CELL_TYPE_NUMERIC: //数字cellValue = String.valueOf(cell.getNumericCellValue());break;case Cell.CELL_TYPE_STRING: //字符串cellValue = String.valueOf(cell.getStringCellValue());break;case Cell.CELL_TYPE_BOOLEAN: //BooleancellValue = String.valueOf(cell.getBooleanCellValue());break;case Cell.CELL_TYPE_FORMULA: //公式cellValue = String.valueOf(cell.getCellFormula());break;case Cell.CELL_TYPE_BLANK: //空值break;default:throw new Exception("存在非法格式的单元格"); //其他类型报错}return cellValue;}/*** 根据文件后缀名获取 workbook** @param is       文件流* @param fileName 文件名称* @return workbook* @throws IOException* @throws BiffException*/public static Workbook getWorkBook(InputStream is, String fileName) throws Exception {Workbook workbook = null;try {//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象if (fileName.endsWith(xls)) {workbook = new HSSFWorkbook(is);} else if (fileName.endsWith(xlsx)) {workbook = new XSSFWorkbook(is);}return workbook;}catch (IOException ex){throw new Exception("生成文件异常IO"+ex.getLocalizedMessage());}catch (Exception ex){throw new Exception("生成文件异常");}finally {if(null!=workbook) {workbook.close();}}}/**** @param inputStream 文件* @param name 文件名称* @param t 传入得对象* @param titleMap 文件读取的数据* @param checkMap 必填值校验* @param <T> 返回的对象* @return* @throws Exception*/public static <T> List<T> excelToDataList(InputStream inputStream,String name,Class<T> t,Map<String, String> titleMap,Map<String, String> checkMap) throws Exception {List<T> lists = new ArrayList<>();Workbook wb = null;try {//根据文件后缀,获取worebookwb = getWorkBook(inputStream, name);if (wb == null) {throw new Exception("创建工作簿失败");}Sheet sheet = wb.getSheetAt(0);//获得当前sheet的开始行int firstRowNum = sheet.getFirstRowNum();//获得当前sheet的结束行int lastRowNum = sheet.getLastRowNum();//第一行 title标题行Row fristRow = sheet.getRow(firstRowNum);//获得第一行的开始列int firstCellNum = fristRow.getFirstCellNum();//获得第一行的列数int lastCellNum = fristRow.getPhysicalNumberOfCells();//excel中每列数据在MerchantImportReq属性的顺序List<String> keyLists = new ArrayList<>();for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {Cell cell = fristRow.getCell(cellNum);if (titleMap.size() == 0) {break;}for (Map.Entry<String, String> entry : titleMap.entrySet()) {String key = entry.getKey();String cellValue = getCellValue(cell);if (null != cellValue) {if (cellValue.trim().equals(key)) {keyLists.add(titleMap.get(key));titleMap.remove(key);break;}}}}//判断是否缺少信息if (lastCellNum < keyLists.size()) {throw new Exception("文件信息不全,缺少列");}//循环除了第一行的所有行  除了title行剩下的都为需要处理的数据for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {//获得当前行Row row = sheet.getRow(rowNum);if (row == null) {continue;}T newT = t.newInstance();//获取FundCostInfoPageResponse对象并放进list中newT = excelTOData(row, keyLists, firstCellNum, lastCellNum, newT);boolean rowNumFlag=false;for (Field f : newT.getClass().getDeclaredFields()) {f.setAccessible(true);if (f.get(newT) != null && StringUtils.isNotBlank((f.get(newT).toString()))) {rowNumFlag=true;break;}}if (null != newT&&rowNumFlag) {JSONObject jsonObject = JSONObject.fromObject(newT);if (!checkObjAllFieldsIsNull(jsonObject, checkMap)) {lists.add(newT);}}}} catch (Exception e) {e.printStackTrace();throw new Exception("资金成本汇总数据解析异常 :" + e.getMessage());}return lists;}/*** 判断对象为空 或者 属性是否全部为空** @param* @return*/public static boolean checkObjAllFieldsIsNull(JSONObject jsonObject, Map<String, String> checkMap) throws Exception{boolean flag = false;if (null == jsonObject) {return true;}for (Map.Entry<String, String> entry : checkMap.entrySet()) {String key = entry.getKey();String value = entry.getValue();String jsonValue=jsonObject.getString(key);if (StringUtils.isEmpty(jsonValue)) {throw new Exception("必填项【" + value + "】字段不能为空!");}boolean dateFlag=true;if(key.equals("startDate")||key.equals("endDate")){dateFlag=DateUtils.isLegalDate(jsonValue.length(),jsonValue,"yyyy-MM-dd");}if(!dateFlag){throw new Exception("【" + value + "】字段格式错误!");}}return flag;}}


http://www.ppmy.cn/news/381610.html

相关文章

JDBC Apache—DBUtils 详解(通俗易懂)

目录 一、前言 二、Apache—DBUtils的引入 1.传统使用ResultSet的缺点 : 2.改进方法 : 3.改进方法的模拟实现 : 三、Apache—DBUtils的使用 1.基本介绍 : 2.准备工作 : 3.DBUtils查询(DQL) : 4.query方法源码分析 : 5.DBUtils处理(DML) : 四、总结 一、前言 第六节…

[学习笔记] [机器学习] 11. EM算法(极大似然估计、EM算法实例、极大似然估计取对数的原因)

视频链接数据集下载地址&#xff1a;无需下载 学习目标&#xff1a; 了解什么是 EM 算法知道极大似然估计知道 EM 算法实现流程 讲 EM 算法主要是为了后面的 HMM 做准备。 1. 初始 EM 算法 EM 算法&#xff08;Expectation-Maximization algorithm&#xff0c;期望最大化算法…

使用yum 源安装nginx

执行以下命令&#xff0c;添加Nginx到yum源。 sudo rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm 添加完之后&#xff0c;执行以下命令&#xff0c;查看是否已经添加成功。 yum search nginx 添加成功之后&#xf…

月入6000+的CSGO游戏搬砖项目操作细节和要求

月入6000的CSGO游戏搬砖项目操作细节和要求 最近咨询CSGO搬砖项目的人较多&#xff0c;在此整理一份统一的项目操作细节和要求。 1、什么是国外Steam游戏装备汇率差项目&#xff1f; 这个项目的基本原理是&#xff1a;购买国外Steam游戏平台上的装备&#xff0c;再在国内网易…

【统计模型】缺失数据处理方法

目录 一、缺失数据定义 二、缺失数据原因 三、缺失数据处理步骤 四、数据缺失机制 1.完全随机缺失&#xff08;MCAR&#xff09; 2.随机缺失&#xff08;MAR&#xff09; 3.非随机、不可忽略缺失&#xff08;NMAR&#xff09; 五、缺失数据处理方法 1.直接删除 2.缺失值…

用python画多来a梦-用python画哆啦a梦

广告关闭 2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个社区产品。未来,我们一起乘风破浪,创造无限可能。 也收到了读者想用 python 画各种图的各种需求。 和一些读者沟通后才知道是学校布置了相关的作业,或者是自己想用这个来做毕业设计。 关于这个问题…

群晖nas(DS423+)和百度云盘互相自动备份

群晖nas提供了云同步功能&#xff0c;使用该功能&#xff0c;可以将百度云盘和群晖nas设置成互为备份&#xff0c;这样我们nas上的的重要数据就有多了一层保护。 通过设置&#xff0c;可以将nas上的某个目录同步到百度云盘的一个目录中&#xff0c;同步的方向可以自行定义&…

二、微机保护的结构框图原理

在实际应用中&#xff0c;微机保护装置分为单CPU和多CPU的结构方式。在中、低压变电所中多数简单的保护装置采用单CPU结构&#xff0c;而在高压及超高压变电所中复杂保护装置广泛采用多CPU的结构方式。 &#xff08;一&#xff09;单 CPU的结构原理 单CPU的微机保护装置是指整套…