ExcelUtil工具类
import com.google.common.base.Strings;
import com.jianwu.util.excel.annotation.ExcelAttribute;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* Created by tookbra on 2016/4/6.
*/
public class ExcelUtil {
private static final Log log = LogFactory.getLog(ExcelUtil.class); public static <T> List<T> importExcel(Class<T> clazz, HSSFWorkbook wb, String sheetName) {
int maxCol = 0;
List<T> list = new ArrayList<T>();
List<T> errorList = new ArrayList<T>(); if(Strings.isNullOrEmpty(sheetName)) {
//没有制定sheet返回null
return null;
}
HSSFSheet sheet = wb.getSheet(sheetName);
if(!sheetName.trim().equals("")) {
// 获取指定sheet
sheet = wb.getSheet(sheetName);
} int rows = sheet.getPhysicalNumberOfRows();
try {
if (rows > 0) {
List<Field> allFields = getMappedFiled(clazz, null); Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (Field field : allFields) {
// 将有注解的field存放到map中.
if (field.isAnnotationPresent(ExcelAttribute.class)) {
ExcelAttribute attr = field.getAnnotation(ExcelAttribute.class);
int col = getExcelCol(attr.column());// 获得列号
maxCol = Math.max(col, maxCol);
field.setAccessible(true);// 设置类的私有字段属性可访问.
fieldsMap.put(col, field);
}
}
for (int i = 2; i < rows; i++) {// 从第3行开始取数据,默认第一行是表头.
HSSFRow row = sheet.getRow(i);
int cellNum = maxCol;
T entity = null;
for (int j = 0; j < cellNum; j++) {
String errorMsg = "";
HSSFCell cell = row.getCell(j);
if (cell == null) {
continue;
}
int cellType = cell.getCellType();
String c = "";
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
c = String.valueOf(cell.getNumericCellValue());
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
c = String.valueOf(cell.getBooleanCellValue());
} else {
c = cell.getStringCellValue();
}
if (c == null || c.equals("")) {
continue;
}
entity = (entity == null ? clazz.newInstance() : entity);// 如果不存在实例则新建.
// System.out.println(cells[j].getContents());
Field field = fieldsMap.get(j);// 从map中得到对应列的field. if (field == null) {
continue;
} // 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType) {
field.set(entity, String.valueOf(c));
} else if ((Integer.TYPE == fieldType)
|| (Integer.class == fieldType)) {
field.set(entity, Integer.parseInt(c));
} else if ((Long.TYPE == fieldType)
|| (Long.class == fieldType)) {
field.set(entity, Long.valueOf(c));
} else if ((Float.TYPE == fieldType)
|| (Float.class == fieldType)) {
field.set(entity, Float.valueOf(c));
} else if ((Short.TYPE == fieldType)
|| (Short.class == fieldType)) {
field.set(entity, Short.valueOf(c));
} else if ((Double.TYPE == fieldType)
|| (Double.class == fieldType)) {
field.set(entity, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(entity, Character
.valueOf(c.charAt(0)));
}
}
}
if (entity != null) {
list.add(entity);
}
}
}
} catch (Exception e) {
e.printStackTrace();
log.error("[importExcel]: {}", e);
}
return list;
} private static List<Field> getMappedFiled(Class clazz, List<Field> fields) {
if (fields == null) {
fields = new ArrayList<Field>();
} Field[] allFields = clazz.getDeclaredFields();
// 所有field并存放到一个list中.
for (Field field : allFields) {
if (field.isAnnotationPresent(ExcelAttribute.class)) {
fields.add(field);
}
}
if (clazz.getSuperclass() != null
&& !clazz.getSuperclass().equals(Object.class)) {
getMappedFiled(clazz.getSuperclass(), fields);
} return fields;
} /**
* 将EXCEL中A,B,C,D,E列映射成0,1,2,3
*
* @param col
*/
public static int getExcelCol(String col) {
col = col.toUpperCase();
// 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
int count = -1;
char[] cs = col.toCharArray();
for (int i = 0; i < cs.length; i++) {
count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
}
return count;
}
}
、、、、、、、、、、、、、、、、、、、、、、、、、、
import com.jianwu.util.excel.RegexType; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* Created by tookbra on 2016/4/7.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAttribute {
/**
* 标题, 该列名对应Excel中第一列的内容
*/
String value() default ""; /**
* 该列是否必须
*/
boolean required() default false; /**
* 列名
* @return
*/
String column(); /**
* 正则表达式校验规则
*
* @return
*/
RegexType regexType() default RegexType.NONE; /**
* 正则规则校验失败错误提示信息
*
* @return
*/
String regexpErrorMessage() default ""; public abstract boolean isExport() default true;
}
、、、、、、、、、、、、、、、、、、、、
/**
* 将EXCEL中A,B,C,D,E列映射成0,1,2,3
*
* @param col
*/
public static int getExcelCol(String col) {
col = col.toUpperCase();
// 从-1开始计算,字母从1开始运算。这种总数下来算数正好相同。
int count = -1;
char[] cs = col.toCharArray();
for (int i = 0; i < cs.length; i++) {
count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
}
return count;
}
、、、、、、、、、、、、、、、
import com.google.common.base.Strings;
import com.jianwu.util.RegexUtils;
import com.jianwu.util.excel.annotation.ExcelAttribute;
import org.apache.commons.lang3.StringUtils; import java.lang.reflect.Field; /**
* Created by tookbra on 2016/4/7.
*/
public class ExcelValidate {
private static ExcelAttribute excelAttribute; public static String valid(Object object) throws Exception{
//获取object的类型
Class<? extends Object> clazz=object.getClass();
//获取该类型声明的成员
Field[] fields = clazz.getDeclaredFields();
//遍历属性
for(Field field:fields){
//对于private私有化的成员变量,通过setAccessible来修改器访问权限
field.setAccessible(true);
String errorMsg = validate(field,object);
//重新设置会私有权限
field.setAccessible(false);
if(Strings.isNullOrEmpty(errorMsg)) {
continue;
}
return errorMsg;
}
return null;
} public static String validate(Field field,Object object) throws Exception{
String description;
Object value;
//获取对象的成员的注解信息
excelAttribute = field.getAnnotation(ExcelAttribute.class);
value = field.get(object);
if(excelAttribute == null) {
return "";
} else {
description = excelAttribute.value();
} if(excelAttribute.required()){
if(value == null || StringUtils.isBlank(value.toString())){
return description + "不能为空";
}
} if(excelAttribute.regexType() != RegexType.NONE){
switch (excelAttribute.regexType()) {
case NONE:
break;
case SPECIALCHAR:
if(RegexUtils.hasSpecialChar(value.toString())){
return excelAttribute.regexpErrorMessage();
}
break;
case EMAIL:
if(!RegexUtils.isEmail(value.toString())){
return excelAttribute.regexpErrorMessage();
}
break;
case IP:
if(!RegexUtils.isIp(value.toString())){
return excelAttribute.regexpErrorMessage();
}
break;
case NUMBER:
if(!RegexUtils.isNumber(value.toString())){
return excelAttribute.regexpErrorMessage();
}
break;
case PHONENUMBER:
if(!RegexUtils.isPhoneNumber(value.toString())){
return excelAttribute.regexpErrorMessage();
}
break;
default:
break;
}
}
return null;
}
}
、、、、、、、、、、、、、、、、
package com.jianwu.util.excel; /**
* Created by tookbra on 2016/4/7.
*/
public enum RegexType {
NONE,
SPECIALCHAR,
EMAIL,
IP,
NUMBER,
PHONENUMBER;
}
、、、、、、、、、、、、、、、、、、、、
import com.google.common.base.Strings;
import com.jianwu.util.excel.annotation.ExcelAttribute;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* Created by tookbra on 2016/4/6.
*/
public class ExcelUtil {
private static final Log log = LogFactory.getLog(ExcelUtil.class); public static <T> List<T> importExcel(Class<T> clazz, HSSFWorkbook wb, String sheetName) {
int maxCol = 0;
List<T> list = new ArrayList<T>();
List<T> errorList = new ArrayList<T>(); if(Strings.isNullOrEmpty(sheetName)) {
//没有制定sheet返回null
return null;
}
HSSFSheet sheet = wb.getSheet(sheetName);
if(!sheetName.trim().equals("")) {
// 获取指定sheet
sheet = wb.getSheet(sheetName);
} int rows = sheet.getPhysicalNumberOfRows();
try {
if (rows > 0) {
List<Field> allFields = getMappedFiled(clazz, null); Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (Field field : allFields) {
// 将有注解的field存放到map中.
if (field.isAnnotationPresent(ExcelAttribute.class)) {
ExcelAttribute attr = field.getAnnotation(ExcelAttribute.class);
int col = getExcelCol(attr.column());// 获得列号
maxCol = Math.max(col, maxCol);
field.setAccessible(true);// 设置类的私有字段属性可访问.
fieldsMap.put(col, field);
}
}
for (int i = 2; i < rows; i++) {// 从第3行开始取数据,默认第一行是表头.
HSSFRow row = sheet.getRow(i);
int cellNum = maxCol;
T entity = null;
for (int j = 0; j < cellNum; j++) {
String errorMsg = "";
HSSFCell cell = row.getCell(j);
if (cell == null) {
continue;
}
int cellType = cell.getCellType();
String c = "";
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
c = String.valueOf(cell.getNumericCellValue());
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
c = String.valueOf(cell.getBooleanCellValue());
} else {
c = cell.getStringCellValue();
}
if (c == null || c.equals("")) {
continue;
}
entity = (entity == null ? clazz.newInstance() : entity);// 如果不存在实例则新建.
// System.out.println(cells[j].getContents());
Field field = fieldsMap.get(j);// 从map中得到对应列的field. if (field == null) {
continue;
} // 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType) {
field.set(entity, String.valueOf(c));
} else if ((Integer.TYPE == fieldType)
|| (Integer.class == fieldType)) {
field.set(entity, Integer.parseInt(c));
} else if ((Long.TYPE == fieldType)
|| (Long.class == fieldType)) {
field.set(entity, Long.valueOf(c));
} else if ((Float.TYPE == fieldType)
|| (Float.class == fieldType)) {
field.set(entity, Float.valueOf(c));
} else if ((Short.TYPE == fieldType)
|| (Short.class == fieldType)) {
field.set(entity, Short.valueOf(c));
} else if ((Double.TYPE == fieldType)
|| (Double.class == fieldType)) {
field.set(entity, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(entity, Character
.valueOf(c.charAt(0)));
}
}
}
if (entity != null) {
list.add(entity);
}
}
}
} catch (Exception e) {
e.printStackTrace();
log.error("[importExcel]: {}", e);
}
return list;
} private static List<Field> getMappedFiled(Class clazz, List<Field> fields) {
if (fields == null) {
fields = new ArrayList<Field>();
} Field[] allFields = clazz.getDeclaredFields();
// 所有field并存放到一个list中.
for (Field field : allFields) {
if (field.isAnnotationPresent(ExcelAttribute.class)) {
fields.add(field);
}
}
if (clazz.getSuperclass() != null
&& !clazz.getSuperclass().equals(Object.class)) {
getMappedFiled(clazz.getSuperclass(), fields);
} return fields;
} /**
* 将EXCEL中A,B,C,D,E列映射成0,1,2,3
*
* @param col
*/
public static int getExcelCol(String col) {
col = col.toUpperCase();
// 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
int count = -1;
char[] cs = col.toCharArray();
for (int i = 0; i < cs.length; i++) {
count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
}
return count;
}
}
ExcelUtil工具类的更多相关文章
- Excelutil 工具类
1.说明:ExcelUtil主要用于获得单元格的数据和对对指定单元格中写入数据用! 相关代码如下: package main.java; import java.io.File; import jav ...
- java中常用的工具类(三)
继续分享java中常用的一些工具类.前两篇的文章中有人评论使用Apache 的lang包和IO包,或者Google的Guava库.后续的我会加上的!谢谢支持IT江湖 一.连接数据库的综合类 ...
- java常用工具类(三)
一.连接数据库的综合类 package com.itjh.javaUtil; import java.sql.Connection; import java.sql.DriverManager; im ...
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
- 导入导出Excel的Java工具类ExcelUtil
在编写ExcelUtil之前,在网上查了一些资料.java中用来处理Excel的第三方开源项目主要就是POI和JXL.poi功能强大,但是比较耗资源,对于大数据量的导入导出性能不是太好:jxl功能简单 ...
- 【原创】POI操作Excel导入导出工具类ExcelUtil
关于本类线程安全性的解释: 多数工具方法不涉及共享变量问题,至于添加合并单元格方法addMergeArea,使用ThreadLocal变量存储合并数据,ThreadLocal内部借用Thread.Th ...
- 基于jdk1.7实现的excel导出工具类
通用excel导出工具类,基于泛型.反射.hashmap 以及基于泛型.反射.bean两种方式 import java.io.*;import java.lang.reflect.Field;impo ...
- 自己封装的poi操作Excel工具类
自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...
- 使用POI插件,提取导出excel的工具类
在网站的不同的模块都需要使用到导入导出excel的功能,我们就需要写一个通用的工具类ExcelUtil. 我的思路:首先,导入和导出的Excel的文件格式固定:主标题,二级标题,数据行(姑且就这么叫) ...
随机推荐
- Java-jdbc连接简化类jdbcUtil
在src文件夹下创建配置文件 db.properties db.properties drivername=com.mysql.jdbc.Driver url=jdbc:mysql://localho ...
- Windoows窗口程序五
程序执行机制 过程驱动-程序的执行过程是按照预订好的顺序执行. 事件驱动-程序的执行是无序,用户可以根据需要随机触发相应的事件. Win32窗口程序就是采用事件驱动方式执行,也就是消息机制. 当系统通 ...
- UML总结---UML九种图关系说明
UML中包括九种图:用例图.类图.对象图.状态图.时序图.协作图.活动图.组件图.配置图. 1)用例图(Use Case Diagram) 它是UML中最简单也是最复杂的一种图.说它简单是因为它采用了 ...
- 自然语言交流系统 phxnet团队 创新实训 个人博客 (二)
因为项目用的到条件编译,遂专门记载: 众所周知在C和CPP中可以通过预处理语句来实现条件编译,但是在java中没有预处理语句,我们该如何实现条件编译呢? 这是一个简单的demo public clas ...
- 关于Cocos2d-x中init方法和onEnter方法的区别
init()和onEnter()这两个方法都是写实例化对象的类(比如继承自Node的一些类等等)的时候用到的方法. 一般都是public类型下面的 bool init(); void onEnter( ...
- 编译 boost 库(win7+boost1.60+vs2008)
参见:http://blog.csdn.net/u013074465/article/details/42532527 下载boost安装包 https://sourceforge.net/proje ...
- SimplifiedHibernate:简化了的Hibernate
我的目的是实现下Hibernate中增删改查.缓存的核心功能.虽然基本功能实现了,但可能还有好多Bug,欢迎点评拍砖,没准能在一片谩骂声中取得意想不到的进步,:) // DatabaseAccess. ...
- Ubuntu:为 Firefox 浏览器 安装 flash 插件
从adobe上下载浏览器flashplayer插件:推荐 x.tar.gz格式的——通用格式. 解压tar.gz后可以得到:libflashplayer.so 文件 将 libflashplayer. ...
- GIS-005-Dojo & jQuery 事件处理
1.添加事件 dojo.connect(dojo.byId("SelectRect"), "onclick", function () { //todo }); ...
- 分享一句话的同时说说遍历map的常用方法
最近在网上看到一句话,鄙人觉得这是比较经典的一句话,首先要给大家分享哈: 当一个人找不到出路的时候,最好的办法就是将当前能做好的事情做到极致,做到无人能及. Map<String, String ...