Java工具类文章目录
第一章 实体类的反射
前言
本文主要介绍一下,关于Excel文件导入到Java实体类中的工具类,依托第一章中所实现的反射注入,以及Excel注解,如果还没阅读过,可以参考下目录
本来中关于Excel工具类部分,受Excel自定义字段导出 文章所启发,在此基础上进行的二次开发了导入工具类,并且均适配了Java 1.6 版本,特别鸣谢文章作者的对思路的分享。
提示:以下是本篇文章正文内容,下面案例可供参考
一、导入类代码
public class ParseExcel {
private ParseExcel() {}
private static Workbook wb;
private static Logger LOGGER = LoggerFactory.getLogger(ParseExcel.class);
/**
* 获取数据
*
* @param excelPath
* @return
* @throws IOException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws IntrospectionException
* @throws InvocationTargetException
* @throws SecurityException
* @throws IllegalArgumentException
*/
public static List<JSONObject> parseDataOfPoJo(String excelPath,
Object objBean) throws IOException, InstantiationException,
IllegalAccessException, ClassNotFoundException,
IllegalArgumentException, SecurityException,
InvocationTargetException, IntrospectionException,
NoSuchMethodException {
File excelFile = new File(excelPath);
//针对2003版本和2007版本进行一个兼容
if (!excelFile.isFile())
throw new RuntimeException("文件不存在");
String fileName = excelFile.getName();
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"xls".equals(suffixName) && !"xlsx".equals(suffixName))
throw new RuntimeException("文件格式不正确");
FileInputStream fis = new FileInputStream(excelFile);
if ("xls".equals(suffixName))
wb = new HSSFWorkbook(fis);
if ("xlsx".equals(suffixName))
wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
// 先获取头行标签
List<String> nameTag = new ArrayList();
for (int i = sheet.getFirstRowNum(); i <= sheet.getFirstRowNum(); i++) {
Row row = sheet.getRow(i);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex <= lastCellIndex; cIndex++) {
Cell cell = row.getCell(cIndex);
if (cell != null) {
cell.setCellType(cell.CELL_TYPE_STRING);
nameTag.add(cell.toString());
}
}
}
}
Class<?> clazz = (Class<?>) objBean.getClass();
LOGGER.info("nowClass"+clazz.getName());
// 头行为标签行 +1为标题行 +2为数据行
int firstRowIndex = sheet.getFirstRowNum() + 2;
int lastRowIndex = sheet.getLastRowNum();
List<JSONObject> list = new ArrayList<JSONObject>();
for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
Object[] obj = new Object[lastCellIndex];
Field[] fs = clazz.getDeclaredFields();
Map<String, Object> map = new HashMap<String, Object>();
for (int cIndex = firstCellIndex; cIndex < nameTag.size(); cIndex++) {
Cell cell = row.getCell(cIndex);
if (cell != null) {
cell.setCellType(cell.CELL_TYPE_STRING);
obj[cIndex] = cell.toString();
for (int i = 0; i < fs.length; i++) {
fs[i].setAccessible(true);
if (fs[i].getName().equals(nameTag.get(cIndex))) {
// 符合标签 判断类型赋值
String type = fs[i].getType().toString();
if (type.equals("class java.lang.Double")) {
if (obj[cIndex].toString().equals("")) {
obj[cIndex] = "0.0";
}
Double valueDouble = Double
.valueOf(obj[cIndex].toString());
String formatString=new BigDecimal(valueDouble).setScale(4, RoundingMode.HALF_UP).toPlainString();
Double forformat = Double.valueOf(formatString);
map.put(nameTag.get(cIndex).toString(),
forformat);
}
if (type.equals("class java.math.BigDecimal")) {
if (obj[cIndex].toString().equals("")) {
obj[cIndex] = "0.0";
}
BigDecimal formatDecimal=new BigDecimal(obj[cIndex].toString()).setScale(4, RoundingMode.HALF_UP);
map.put(nameTag.get(cIndex).toString(),
formatDecimal);
}
if (type.equals("class java.lang.Integer")) {
if (obj[cIndex].toString().equals("")) {
obj[cIndex] = "0";
}
Integer valueInteger = Integer
.valueOf(obj[cIndex].toString());
map.put(nameTag.get(cIndex).toString(),
valueInteger);
}
if (type.equals("class java.lang.String")) {
map.put(nameTag.get(cIndex).toString(),
obj[cIndex].toString());
}
}
}
}
}
String mapJson = JSON.toJSONString(map);
JSONObject objjson = JSON.parseObject(mapJson);
list.add(objjson);
}
}
return list;
}
}
二、使用得Excel样式
根据代码中的取数,可以把模板文件分为标题栏和标签栏,标签栏对应实体类属性名,标题栏对应中文注解,而且由于因为是用注解定位的缘故,模板中的字段可以随意移动排列。只要保证标签栏和标题栏一一对应即可。
交换位置并不会影响注入
三、使用方法
List<JSONObject> parseDataOfPoJo(String excelPath,Object objBean)
Excel数据转JsonObject数组
@Param String excelPath =>excel文件路径
@Param Object objBean =>实体类
使用parseDataOfPojo进行导入实体类映射
List<JSONObject> parseData = ParseExcel.parseDataOfPoJo("C:/Users//Desktop/template.xls",new Test());
List<Test> pojoList =new ArrayList<Test>();
//提取List<JSONObject>里的数据映射到实体类集合
Testpojo =new Test();
for(int i=0;i<parseData.size();i++){
pojo = JSONObject.parseObject(parseData.get(i).toString(), Test.class);
pojoList.add(pojo);
}
总结
以上就是本文要讲的内容,本文仅仅简单介绍了导入类的使用,结合后续的导出以及数据处理类使用,对开发过程中能提供不少便利