excel工具类

import com.iport.framework.util.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.Field;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*; /**
* Created by admin on 2016/8/26.
*/
public class PoiUtil {
private static Logger logger = Logger.getLogger(PoiUtil.class); public static <T> List<T> getExcelData(String mapFilePath, Class<T> cla, InputStream inputStream) throws Exception{
List<T> dataList = new ArrayList<T>();
//获取配置数据
JaxbUtil jaxb = new JaxbUtil(TemplateExcelMap.class);
TemplateExcelMap template = jaxb.fromPath(mapFilePath, false);
List<ExcelMap> mapList = template.getColumnList();
Map<String,String> nameFieldMap = new HashMap<String,String>();
Map<Integer,Field> IndexFieldMap = new HashMap<Integer,Field>();
Map<Integer,ExcelMap> mapMap = new HashMap<Integer,ExcelMap>();
Map<String,ExcelMap> strMap = new HashMap<String,ExcelMap>();
for(ExcelMap m : mapList){
nameFieldMap.put(m.getColumnName().trim(), m.getFieldName());
strMap.put(m.getColumnName().trim(), m);
} Workbook book = getWorkbook(inputStream);
Sheet sheet = book.getSheetAt(0);
Row row0 = sheet.getRow(0);
int celNum = row0.getPhysicalNumberOfCells(); //头部数据获取映射
for(int i=0; i<celNum; i++){
Cell cell = row0.getCell(i);
String headDesc = cell.getStringCellValue();
if(!ValidateUtil.isEmpty(headDesc)){
if(nameFieldMap.containsKey(headDesc.trim())){
String fieldName = nameFieldMap.get(headDesc.trim());
IndexFieldMap.put(i, getField(fieldName, cla));
mapMap.put(i, strMap.get(headDesc.trim()));
}
}
}
long s = System.currentTimeMillis();
int rowNum = sheet.getPhysicalNumberOfRows();
Set<Integer> keys = IndexFieldMap.keySet();
if(keys.size() > 0){
for(int i=1;i<rowNum;i++){
Row row = sheet.getRow(i);
T vo = (T)cla.newInstance();
for(Integer columIndex : keys){
Cell cel = row.getCell(columIndex);
Field field = IndexFieldMap.get(columIndex);
ExcelMap mapping = mapMap.get(columIndex);
Object o = getCellValue(cel, field.getType(), mapping);
//try{
field.set(vo,o);
// }catch (Exception e){
// e.printStackTrace();
//} }
dataList.add(vo);
}
}
long e = System.currentTimeMillis();
logger.debug("数据导入解析耗时:"+(e-s));
return dataList;
} public static Workbook getWorkbook(InputStream inputStream) throws IOException, InvalidFormatException {
Workbook book = null;
if (!(inputStream.markSupported())) {
inputStream = new PushbackInputStream(inputStream, 8);
}
if (POIFSFileSystem.hasPOIFSHeader(inputStream)) {
book = new HSSFWorkbook(inputStream);
} else if (POIXMLDocument.hasOOXMLHeader(inputStream)) {
book = new XSSFWorkbook(OPCPackage.open(inputStream));
}
return book;
} private static Field getField(String filedName, Class cla) throws Exception{
Field field = cla.getDeclaredField(filedName);
if(field!=null){
field.setAccessible(true);
}
return field;
}; /**
* 获取单元格内容
* @param cell
* @param fieldClass
* @param mapping
* @return
* @throws Exception
*/
private static Object getCellValue(Cell cell, Class fieldClass, ExcelMap mapping) throws Exception{
if (cell == null) {
return null;
}
Object result = null;
if ("class java.util.Date".equals(fieldClass.toString()) || ("class java.sql.Time").equals(fieldClass.toString())) {
if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
result = cell.getDateCellValue();
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
result = getDateData(mapping, cell.getStringCellValue());
}
if ( result != null && ("class java.sql.Time").equals(fieldClass.toString())) {
result = new Time(((Date) result).getTime());
}
} else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
double doubleVal = cell.getNumericCellValue();
if("class java.lang.Double".equals(fieldClass.toString())){
result = doubleVal;
}else{
long longVal = Math.round(cell.getNumericCellValue());
if(Double.parseDouble(longVal + ".0") == doubleVal){
try{
result = (int) longVal;
}catch (Exception e){
result = longVal;
}
}else {
result = doubleVal;
}
}
} else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
result = cell.getBooleanCellValue();
} else {
result = cell.getStringCellValue();
if(ValidateUtil.isEmpty((String)result)){
result = null;
}
}
return result;
} /**
* 获取日期类型数据
*
* @Author JueYue
* @date 2013年11月26日
* @param entity
* @param value
* @return
*/
private static Date getDateData(ExcelMap entity, String value) {
String formatStr = entity.getFormat();
if(!ValidateUtil.isEmpty(formatStr)){
String[] formats = formatStr.split(";");
for(int i = 0; i<formats.length; i++){
try{
Date d = formartData(formats[i], value);
if(d!=null){
return d;
}
}catch (Exception e){
logger.error(formats[i]+"日期转换"+value+"异常" + e.getMessage());
}
}
}
return null;
} private static Date formartData(String formatStr, String value){
if (StringUtils.isNotEmpty(formatStr) && StringUtils.isNotEmpty(value)) {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
try {
return format.parse(value);
} catch (ParseException e) {
throw new RuntimeException("Excel 值获取失败");
}
}
return null;
} }

excel工具类的更多相关文章

  1. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

  2. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  3. javaEE开发之导出excel工具类

    web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...

  4. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  5. java 解析excel工具类

      java 解析excel工具类 CreateTime--2018年3月5日16:48:08 Author:Marydon ReadExcelUtils.java import java.io.Fi ...

  6. Java解析Excel工具类(兼容xls和xlsx)

    依赖jar <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml&l ...

  7. java里poi操作Excel工具类【我改】

    参考原文: https://www.cnblogs.com/yizhang/p/7244917.html 我改: package test; import java.io.File; import j ...

  8. java操作excel 工具类

    java操作excel 可参考https://blog.csdn.net/xunwei0303/article/details/53213130 直接上代码: 一.java生成excel文件: pac ...

  9. Python Excel工具类封装, 给excel表头搞点颜色

    封装Excel工具类 我们常用的excel工具类,读有xlrd,写有xlwt.有读有写,新一代库有pandas,openpyxl等等. 大家用法都差不多,今天博主就介绍新手最爱,我也爱的xlrd和xl ...

随机推荐

  1. SQL SERVER 数据库各版本功能对比

    以前写了篇SQL SERVER 2008数据库各版本功能对比,官网提供的那个功能确实很好很强大,后面发现那个链接失效了.今天又遇到要对比SQL Server 2014数据库版本功能需求,搜索找了好久才 ...

  2. 让OData和NHibernate结合进行动态查询

    OData是一个非常灵活的RESTful API,如果要做出强大的查询API,那么OData就强烈推荐了.http://www.odata.org/ OData的特点就是可以根据传入参数动态生成Ent ...

  3. sql语句查询经纬度范围(转载,源链接失效)

    MySQL性能调优 – 使用更为快速的算法进行距离 最近遇到了一个问题,通过不断的尝试最终将某句原本占据近1秒的查询优化到了0.01秒,效率提高了100倍. 问题是这样的,有一张存放用户居住地点经纬度 ...

  4. Ubuntu apt 常用命令

     APT(the Advanced Packaging Tool)是Ubuntu 软件包管理系统的高级界面,Ubuntu 是基于Debian的,APT由几个名字以“apt-”打头的程序组成.apt-g ...

  5. gcc/linux内核中likely、unlikely和__attribute__(section(""))属性

    查看linux内核源码,你会发现有很多if (likely(""))...及if (unlikely(""))...语句,这些语句其实是编译器的一种优化方式,具 ...

  6. kettle中含有参数传递的定时任务

    (1)新建一个作业(新建->作业),并在控制面板右键: (2)设置一个命令参数: (3)把作业的参数传递给转换: (4)在转换中右键设置转换属性: (5)接收作业中设置的传递参数: (6)参数的 ...

  7. Linux中C程序调试、makefile

    gcc基本语法格式:gcc [-选项] 源文件 [-选项] 目标文件,GCC编译C程序的过程: 预处理:gcc -E hello.c hello.i.-E指定执行到预处理结束,下面类似. 编译:gcc ...

  8. 监控系统Opserver的配置调试

    Stack Exchange开源其监控系统Opserver有一段时间了.之前在项目中用过他们的MiniProfile来分析页面执行效率和帮助新人了解项目,当他们开源了其监控系统的时候正好部门也在关注监 ...

  9. spring.net 框架分析(三)ContextRegistry.GetContext()

    我们通过ContextRegistry.GetContext()建立了一个IApplicationContext得实例,那么这个实例具体是怎么建立的了. 我们来分析一下容器实例建立的过程: 我们在配置 ...

  10. 4种解决json日期格式问题的办法

    4种解决json日期格式问题的办法   开发中有时候需要从服务器端返回json格式的数据,在后台代码中如果有DateTime类型的数据使用系统自带的工具类序列化后将得到一个很长的数字表示日期数据,如下 ...