java poi 注解_Java POI注解方式---Excel文件导入工具类实现

本文介绍了一个用于处理Excel文件的Java工具类,该工具能够读取指定路径下的Excel文件,并将其内容转换为Java对象集合。文章详细解释了如何通过反射机制处理不同类型的Excel单元格数据,并提供了灵活的数据类型转换方法。

package com.oa.manager.vcms.util;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.DateUtil;

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 java.io.FileInputStream;

import java.io.InputStream;

import java.lang.reflect.Field;

import java.math.BigDecimal;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

public class ExcelImportUtil {

private Class clazz;

private Field fields[];

public ExcelImportUtil(Class clazz) {

this.clazz = clazz;

fields = clazz.getDeclaredFields();

}

/**

* 读取excel

* @param is

* @param rowIndex

* @param cellIndex

* @return

*/

@SuppressWarnings({ "unused" })

public List readExcel(String filePath, int rowIndex,int cellIndex) {

InputStream is = null;

try {

is = new FileInputStream(filePath);

//WorkbookFactory工厂类生产出对应版本的Excel的workbook具体对象

Workbook workbook = WorkbookFactory.create(is);

Sheet sheet = workbook.getSheetAt(0);

// 不准确

int rowLength = sheet.getLastRowNum()+1;

System.out.println("sheet总行数:"+(sheet.getLastRowNum()+1));

return this.readExcelData(sheet, rowIndex, cellIndex);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 收集Excel中的数据

*/

public List readExcelData(Sheet sheet, int rowIndex,int cellIndex) {

List list = new ArrayList();

for (int rowNum = rowIndex; rowNum <= sheet.getLastRowNum(); rowNum++) {

Row row = sheet.getRow(rowNum);

T entity = null;

try {

entity = this.covertObject(row, cellIndex);

list.add(entity);

} catch (Exception e) {

}

}

return list;

}

/**

* Excel每一行数据转换为对象

* @param row

* @param cellIndex

* @return

* @throws Exception

*/

public T covertObject(Row row,int cellIndex) throws Exception {

T entity = (T) clazz.newInstance();

for (int cellNum = cellIndex; cellNum < row.getLastCellNum(); cellNum++) {

Cell cell = row.getCell(cellNum);

for (Field field : fields) {

if(field.isAnnotationPresent(ExcelAttribute.class)){

field.setAccessible(true);//设置为可以访问私有变量

ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);

if(cellNum == ea.sort()) {

field.set(entity, covertAttrType(field, cell));

}

}

}

}

return entity;

}

/**

* 类型转换 将cell 单元格格式转为 字段类型

* @throws ParseException

*/

private Object covertAttrType(Field field, Cell cell) throws NumberFormatException, ParseException {

String fieldType = field.getType().getSimpleName();

if ("String".equals(fieldType)) {

return getValue(cell);

}else if ("Date".equals(fieldType)) {

return new SimpleDateFormat("yyyy-MM-dd").parse(getValue(cell)) ;

}else if ("int".equals(fieldType) || "Integer".equals(fieldType)) {

return Integer.parseInt(getValue(cell));

}else if ("long".equals(fieldType) || "Long".equals(fieldType)) {

return Long.parseLong(getValue(cell));

}else if ("double".equals(fieldType) || "Double".equals(fieldType)) {

return Double.parseDouble(getValue(cell));

}else {

return null;

}

}

/**

* 格式转为String

* @param cell

* @return

*/

public String getValue(Cell cell) {

if (cell == null) {

return "";

}

switch (cell.getCellType()) {

case Cell.CELL_TYPE_STRING:

return cell.getRichStringCellValue().getString().trim();

// 数字类型 小数,整数,日期

case Cell.CELL_TYPE_NUMERIC:

if (DateUtil.isCellDateFormatted(cell)) {

Date dt = cell.getDateCellValue();

//DateUtil.getJavaDate(cell.getNumericCellValue());

System.out.println("日期:"+new SimpleDateFormat("yyyy-MM-dd").format(dt));

return new SimpleDateFormat("yyyy-MM-dd").format(dt);

} else {

// 防止数值变成科学计数法

String strCell = "";

Double num = cell.getNumericCellValue();

BigDecimal bd = new BigDecimal(num.toString());

if (bd != null) {

strCell = bd.toPlainString();

}

// 去除 浮点型 自动加的 .0

if (strCell.endsWith(".0")) {

strCell = strCell.substring(0, strCell.indexOf("."));

}

return strCell;

}

case Cell.CELL_TYPE_BOOLEAN:

return String.valueOf(cell.getBooleanCellValue());

case Cell.CELL_TYPE_FORMULA://公式类型

return cell.getCellFormula();

//其余的单元格类型统一返回""

default:

return "";

}

}

}

自己封装的excel导出/导入,可以根据注解来导出excel.本项目一共有13个类,里面还包含了一个反射工具,一个编码工具,10分值了。下面是测试代码 public class Test { public static void main(String[] arg) throws FileNotFoundException, IOException{ testBean(); testMap(); } public static void testBean() throws FileNotFoundException, IOException{ List l = new ArrayList(); for(int i=0;i<100;i++){ l.add(new MyBean()); } //很轻松,只需要二句话就能导出excel BeanExport be = ExportExcel.BeanExport(MyBean.class); be.createBeanSheet("1月份", "1月份人员信息").addData(l); be.createBeanSheet("2月份","2月份人员信息").addData(l); be.writeFile("E:/test/bean人员信息8.xlsx"); } //如果不想用注解,还能根据MAP导出. public static void testMap () throws FileNotFoundException, IOException{ List l = new ArrayList(); l.add(new MapHeader("姓名","name",5000)); l.add(new MapHeader("年龄","age",4000)); l.add(new MapHeader("生日","birthdate",3000)); l.add(new MapHeader("地址","address",5000)); l.add(new MapHeader("双精度","d",4000)); l.add(new MapHeader("float","f",6000)); List<Map> lm = new ArrayList<Map>(); for(int i=0;i<100;i++){ Map map = new HashMap(); map.put("name","闪电球"); map.put("age",100); map.put("birthdate",new Date()); map.put("address","北京市广东省AAA号123楼!"); map.put("d",22.222d); map.put("f",295.22f); lm.add(map); } MapExport me = ExportExcel.mapExport(l); me.createMapSheel("1月份","广东省人员信息").addData(lm); me.createMapSheel("2月份", "北京市人员信息").addData(lm); me.writeFile("E:/test/map人员信息9.xlsx"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值