excel工具类
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工具类的更多相关文章
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
- 自己封装的poi操作Excel工具类
自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...
- javaEE开发之导出excel工具类
web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- java 解析excel工具类
java 解析excel工具类 CreateTime--2018年3月5日16:48:08 Author:Marydon ReadExcelUtils.java import java.io.Fi ...
- Java解析Excel工具类(兼容xls和xlsx)
依赖jar <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml&l ...
- java里poi操作Excel工具类【我改】
参考原文: https://www.cnblogs.com/yizhang/p/7244917.html 我改: package test; import java.io.File; import j ...
- java操作excel 工具类
java操作excel 可参考https://blog.csdn.net/xunwei0303/article/details/53213130 直接上代码: 一.java生成excel文件: pac ...
- Python Excel工具类封装, 给excel表头搞点颜色
封装Excel工具类 我们常用的excel工具类,读有xlrd,写有xlwt.有读有写,新一代库有pandas,openpyxl等等. 大家用法都差不多,今天博主就介绍新手最爱,我也爱的xlrd和xl ...
随机推荐
- SQL*Plus环境下创建PLUSTRACE角色
普通用户在SQL*Plus中开启AUTOTRACE报告时,遇到SP2-0618: Cannot find the Session Identifier. Check PLUSTRACE role is ...
- archlinux 加载loop模块,且设定loop设备个数
如果loop模块没有编译进内核就要先加载loop模块 modprobe loop 然后更改/etc/modprobe.d/modprobe.conf(有些文章写是在/etc/modprobe.conf ...
- Git各大平台(win/Linux/Mac)图形化界面客户端大汇总
摘要: 介绍各平台下的图形化界面git客户端(本人并没有全部使用过),欢迎大家补充新的软件或者使用感受~ 一.TortoiseGit - The coolest Interface to Git V ...
- 搭建SVN服务器
系统环境:CentOS 6.6 首先查看服务器上是否已安装了svn # rpm -qa subversion 如果没有安装,则执行此命令 # yum list subversion ...
- mysql 基础 增删改查语句
MySQL:众多关系型数据库中的一种仓库 --数据库箱子 --表数据库:进入mysql 命令行: mysql -uroot -p查看所有数据库: show databases;创建数据库: creat ...
- [No0000A3]护眼谎言大揭秘,选择正确的方式保护眼睛!
当眼睛因为过度劳累而状况频出的时候,许多人没有选择极目远眺.眼保健操.充分睡眠等简单易行的养眼方式,而是求助于各种护眼工具.于是,在视疲劳成为常见眼病之后,护眼市场产品层出不穷:护眼灯.眼贴.眼保仪. ...
- 【repost】JS原型与原型链终极详解
一. 普通对象与函数对象 JavaScript 中,万物皆对象!但对象也是有区别的.分为普通对象和函数对象,Object ,Function 是JS自带的函数对象.下面举例说明 function f ...
- [LeetCode] Plus One 加一运算
Given a non-negative number represented as an array of digits, plus one to the number. The digits ar ...
- C#进阶系列——WebApi 跨域问题解决方案:CORS
前言:上篇总结了下WebApi的接口测试工具的使用,这篇接着来看看WebAPI的另一个常见问题:跨域问题.本篇主要从实例的角度分享下CORS解决跨域问题一些细节. WebApi系列文章 C#进阶系列— ...
- 工作邮件loop的用法
examples come from native speaker Put john in the loop about this. He will have good advice. Why hav ...