importExcel运用注解实现EXCEL导入poi类
JAVA报表
package com.app.common.excel;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.app.common.excel.annotation.ExcelAnnotation;
import com.app.common.utils.StringUtils;
/**
* EXCEL通用导入(根据annotation判断导入字段)
*
* @author ZhouBo
*
* @param <T>,Model对象
* @since 2011-07-12
*/
public class ExcelImport<T> {
Class<T> clazz;
public ExcelImport(Class<T> clazz) {
this.clazz = clazz;
}
@SuppressWarnings("unchecked")
public Collection<T> importExcel(File file, String... pattern) {
Collection<T> dist = new ArrayList();
try {
/**
* 类反射得到调用方法
*/
// 得到目标目标类的所有的字段列表
Field filed[] = clazz.getDeclaredFields();
// 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
Map fieldmap = new HashMap();
// 循环读取所有字段
for (int i = 0; i < filed.length; i++) {
Field f = filed[i];
// 得到单个字段上的Annotation
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
// 如果标识了Annotationd的话
if (exa != null) {
// 构造设置了Annotation的字段的Setter方法
String fieldname = f.getName();
String setMethodName = "set"
+ fieldname.substring(0, 1).toUpperCase()
+ fieldname.substring(1);
// 构造调用的method,
Method setMethod = clazz.getMethod(setMethodName,
new Class[] { f.getType() });
// 将这个method以Annotaion的名字为key来存入。
fieldmap.put(exa.exportName(), setMethod);
}
}
/**
* excel的解析开始
*/
// 将传入的File构造为FileInputStream;
FileInputStream in = new FileInputStream(file);
// // 得到工作表
HSSFWorkbook book = new HSSFWorkbook(in);
// // 得到第一页
HSSFSheet sheet = book.getSheetAt(0);
// // 得到第一面的所有行
Iterator<HSSFRow> row = sheet.rowIterator();
/**
* 标题解析
*/
// 得到第一行,也就是标题行
HSSFRow title = row.next();
// 得到第一行的所有列
Iterator<HSSFCell> cellTitle = title.cellIterator();
// 将标题的文字内容放入到一个map中。
Map titlemap = new HashMap();
// 从标题第一列开始
int i = 0;
// 循环标题所有的列
while (cellTitle.hasNext()) {
HSSFCell cell = cellTitle.next();
String value = cell.getStringCellValue();
titlemap.put(i, value);
i = i + 1;
}
/**
* 解析内容行
*/
// 用来格式化日期的DateFormat
SimpleDateFormat sf;
if (pattern.length < 1) {
sf = new SimpleDateFormat("yyyy-MM-dd");
} else
sf = new SimpleDateFormat(pattern[0]);
int w = 0;
while (row.hasNext()) {
// 标题下的第一行
HSSFRow rown = row.next();
// 行的所有列
//Iterator<HSSFCell> cellbody = rown.cellIterator();
// 得到传入类的实例
T tObject = clazz.newInstance();
short k = 0;
// 遍历一行的列
w++;
//while (cellbody.hasNext()) {
for(k=0; k < title.getLastCellNum(); k++) {
//HSSFCell cell = cellbody.next();
HSSFCell cell = rown.getCell(k);
// 这里得到此列的对应的标题
String titleString = (String) titlemap.get((int)k);
// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
if (fieldmap.containsKey(titleString)) {
Method setMethod = (Method) fieldmap.get(titleString);
// 得到setter方法的参数
Type[] ts = setMethod.getGenericParameterTypes();
// 只要一个参数
String xclass = ts[0].toString();
String cons = null;
if (cell == null) {
cons = "";
continue;
}
else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
cons = cell.getStringCellValue();
}
else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
if(HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cons = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate();
} else {
// 是否为数值型
double d = cell.getNumericCellValue();
if (d - (int) d < Double.MIN_VALUE) {
// 是否为int型
cons = Integer.toString((int) d);
} else {
System.out.println("double.....");
// 是否为double型
DecimalFormat df = new DecimalFormat("#");
cons = df.format(cell.getNumericCellValue());
}
}
}
///
/*
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
DateFormat format = new SimpleDateFormat(DateUtil.YYYY_MM_DD);
if(HSSFDateUtil.isCellDateFormatted(cell)) {
// 是否为日期型
str = format.format(cell.getDateCellValue());
} else {
// 是否为数值型
double d = cell.getNumericCellValue();
if (d - (int) d < Double.MIN_VALUE) {
// 是否为int型
str = Integer.toString((int) d);
} else {
System.out.println("double.....");
// 是否为double型
str = Double.toString(cell.getNumericCellValue());
}
}
System.out.println("type=="+cell.getCellType() );
System.out.println("cell=="+str);
}else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
str = cell.getRichStringCellValue().getString();
}else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
str = cell.getCellFormula();
}else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
str = " ";
}else if (cell.getCellType() == HSSFCell.CELL_TYPE_ERROR) {
str = " ";
}
*/
///
if (StringUtils.hasText(cons)
&& cons.indexOf(".0") != -1) {
cons = cons.substring(0, cons.indexOf(".0"));
}
// 判断参数类型
if (xclass.equals("class java.lang.String")) {
setMethod.invoke(tObject, cons);
} else if (xclass.equals("class java.util.Date")) {
setMethod.invoke(tObject, sf.parse(cons));
} else if (xclass.equals("class java.lang.Boolean")) {
Boolean boolname = true;
if (cell.getStringCellValue().equals("否")) {
boolname = false;
}
setMethod.invoke(tObject, boolname);
} else if (xclass.equals("class java.lang.Integer")) {
// 截取小数点
if (StringUtils.hasText(cons)) {
if (cons.indexOf(".") >= 0)
cons = cons.substring(0, cons.indexOf("."));
setMethod.invoke(tObject, new Integer(cons));
}
} else if (xclass.equals("class java.lang.Long")) {
setMethod.invoke(tObject, new Long(cons));
}
}
// 下一列
//k = k + 1;
}
//}
dist.add(tObject);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dist;
}
}
要导入的实体类
/** 贷款联系人 */
@ExcelAnnotation(exportName = "联系人", exportFieldWidth = 60, exportConvertSign = 0, importConvertSign = 0)
private String linkMan;
/** 贷款联系人电话 */
@ExcelAnnotation(exportName = "联系人电话", exportFieldWidth = 60, exportConvertSign = 0, importConvertSign = 0)
private String linkTel;
/** 联系人职务 */
@ExcelAnnotation(exportName = "联系人职务", exportFieldWidth = 60, exportConvertSign = 0, importConvertSign = 0)
private String linkJob;
/** 联系人邮箱 */
@ExcelAnnotation(exportName = "联系人邮箱", exportFieldWidth = 60, exportConvertSign = 0, importConvertSign = 0)
private String linkMail;
/** 添加人 */
@ExcelAnnotation(exportName = "跟踪人", exportFieldWidth = 60, exportConvertSign = 0, importConvertSign = 0)
需要导入的字段就加上@ExcelAnnotation
excel表头跟 exportName一致就可以自动识别导入
importExcel运用注解实现EXCEL导入poi类的更多相关文章
- Excel导入工具类
项目需要从Excel导入数据,然后插入到数据库对应表中.设计了一个导入工具类,导入数据和导入结果如下图示: poi jar版本采用的3.15 导入工具类实现如下: package com.alphaj ...
- Excel导入工具类兼容xls和xlsx
package com.bj58.finance.platform.operation.provider.util; import org.apache.log4j.Logger; import or ...
- 不依赖Excel是否安装的Excel导入导出类
本文利用第三方开源库NPOI实现Excel97-2003,Excel2007+的数据导入导出操作. 不依赖Office是否安装.NPOI开源项目地址:http://npoi.codeplex.com/ ...
- .net core 基于NPOI 的excel导入导出类,支持自定义导出哪些字段,和判断导入是否有失败的记录
#region 从Excel导入 //用法 //var cellHeader = new Dictionary<string, string>(); //cellHeader.Add(&q ...
- 一个基于POI的通用excel导入导出工具类的简单实现及使用方法
前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...
- 170313、poi:采用自定义注解的方式导入、导出excel(这种方式比较好扩展)
步骤一.自定义注解 步骤二.写Excel泛型工具类 步骤三.在需要导出excel的类属相上加上自定义注解,并设置 步骤四.写service,controller 步骤一:自定义注解 import ja ...
- POI导入导出excel(附工具类)
关于POI导出excel的功能我在前面的文章已经写过了,POI导出excel的三种方式 , 导出表格数据到excel并下载(HSSFWorkbook版) ,本篇文章主要是将导入导出功能进一步地封装,在 ...
- Java基于注解和反射导入导出Excel
代码地址如下:http://www.demodashi.com/demo/11995.html 1. 构建项目 使用Spring Boot快速构建一个Web工程,并导入与操作Excel相关的POI包以 ...
- POI之Excel导入
1,maven配置 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-oox ...
随机推荐
- android智能天气闹钟应用开发经过
开发这个应用的初衷是这样产生滴,和我一块租房的同学每天早上都是骑单车上班,所以手机闹钟就会定一个刚好适合骑车的起床时间点.但是呢,有一天早上起床以后发现外面下挺大雨,肯定是不能骑车去上班了,于是就只好 ...
- Codeforces Round #310 (Div. 2)--A(简单题)
http://codeforces.com/problemset/problem/556/A 题意:给一个01字符串,把所有相邻的0和1去掉,问还剩下几个0和1. 题解:统计所有的0有多少个,1有多少 ...
- [功能帮助类] C#RandomHelper随机数,随机字符,可限制范围-帮助类 (转载)
点击下载 RandomHelper.rar 主要功能如下 .生成一个指定范围的随机整数,该随机数范围包括最小值,但不包括最大值 .生成一个0.0到1.0的随机小数 .对一个数组进行随机排序 . 一:随 ...
- 从腾讯QQgame高性能服务器集群架构看“分而治之”与“自治”等分布式架构设计原则
转载:http://space.itpub.net/17007506/viewspace-616852 腾讯QQGame游戏同时在线的玩家数量极其庞大,为了方便组织玩家组队游戏,腾讯设置了大量游戏室( ...
- Java写一个简单学生管理系统
其实作为一名Java的程序猿,无论你是初学也好,大神也罢,学生管理系统一直都是一个非常好的例子,初学者主要是用数组.List等等来写出一个简易的学生管理系统,二.牛逼一点的大神则用数据库+swing来 ...
- 冒泡排序--c#
//冒泡排序 Console.WriteLine("请输入一个程序的数值"); int[] array = { 111, 2, 5, 32, 321 }; int temp = 0 ...
- boost 1.56.0 编译
编译步骤及参数说明: http://www.cnblogs.com/zhcncn/p/3950477.html 编译64位版本: http://www.cnblogs.com/codingmylife ...
- PHP过滤常用标签的正则表达式
$str=preg_replace("/\s+/", " ", $str); //过滤多余回车 $str=preg_replace("/<[ ] ...
- 获取动态SQL查询语句返回值(sp_executesql)
在写存储过程时经常会遇到需要拼接SQL语句的情况,一般情况下仅仅是为了执行拼接后的语句使用exec(@sql)即可. 而今天的一个存储过程却需要获取动态SQL的查询结果. 需求描述:在某表中根据Id值 ...
- linux安装git方法(转)
转自:http://jingyan.baidu.com/article/e9fb46e16698687521f766ec.html 以下内容亲测,确实可行. 由于我的机器是linux6.7,所以省略了 ...