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的文件格式固定:主标题,二级标题,数据行(姑且就这么叫) ...
随机推荐
- js学习笔记10----字符串的基本操作
1.字符串的基本操作如下: 定义字符串: var str = "Hello World!" 字符串的基本操作如下: str.length-----返回字符串长度,这里返回12 st ...
- Java打印整数的二进制表示(代码与解析)
Java打印整数的二进制表示(代码与解析) int a=-99; for(int i=0;i<32;i++){ int t=(a & 0x80000000>>>i)&g ...
- Intellij IDEA:maven的本地仓库问题
不知是否我个人的问题,Intellij IDEA中设置的 maven本地仓库的位置 经常失效,动辄变回默认的路径(~/.m2/repository),然后疯狂下载内容. 很抓狂! 今天认真思考了一番, ...
- JAVA 多线程机制(一)
PS:又开始忙叨JAVA了..前一阵子搞定了HTML+CSS,要开始写实验室的界面了,真没劲...博客到时候再更新吧! 先更新JAVA的吧... 多线程(一) 主要内容 1.JAVA中的线程 2.用T ...
- 修改Java标准库源码
以下是摘抄,实际操作没有测试 先前我曾提到,原本想借由“改动Java标准库源码”来测知Class object的生成,但由于其ctor原始设计为private,也就是说不可能透过这个管道生成Cla ...
- php对gzip的使用(开启)
gzip是一种压缩算法,在网络通信过程中,经常用到gzip压缩算法.比如一个文本文件,大小为100M,使用gzip压缩之后,大小可能会变成几M.在网络传输过程中,传10M和传100M,消耗的时间和带宽 ...
- Oracle-批量修改语句及相关知识点
问: 有两张表A和B,结构相同,数据量一致,比如都有x,y和z列且都有n行,x为主键,完全相等,如何把表B的y列的数据赋值给A的y列? 我写的是1 update A set A.y=B.y where ...
- J2SE基础:8.系统经常使用类二
1:基础数据与封装类型之间的转型 A:基础数据类型--->封装类型(对象类型) Boolean boolean_1 = new Boolean(true); byte ---->Byte ...
- Oracle RAC:使用 NFS 共享存储时的 mount 选项 总结
oracle rac 使用nfs作为共享存储时,mount的选项有 要求,不能随便设置 grid的要求: rw,bg,hard,nointr,rsize=32768,wsize=32768, ...
- Linux Shell脚本面试25个经典问答
1 Shell脚本是什么.它是必需的吗? 答:一个Shell脚本是一个文本文件,包含一个或多个命令.作为系统管理员,我们经常需要使用多个命令来完成一项任务,我们可以添加这些所有命令在一个文本文件(Sh ...