importExcel运用注解实现EXCEL导入poi类

简介: JAVA报表 package com.app.common.excel; import java.io.File; import java.io.FileInputStream; import java.

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一致就可以自动识别导入

河南省豫资城乡投资发展有限公司

目录
相关文章
|
SQL 存储 数据库
excel导入sql数据库
将Excel数据导入SQL数据库是一个相对常见的任务,可以通过多种方法来实现。以下是一些常用的方法: ### 使用SQL Server Management Studio (SSMS) 1
|
存储 Java easyexcel
招行面试:100万级别数据的Excel,如何秒级导入到数据库?
本文由40岁老架构师尼恩撰写,分享了应对招商银行Java后端面试绝命12题的经验。文章详细介绍了如何通过系统化准备,在面试中展示强大的技术实力。针对百万级数据的Excel导入难题,尼恩推荐使用阿里巴巴开源的EasyExcel框架,并结合高性能分片读取、Disruptor队列缓冲和高并发批量写入的架构方案,实现高效的数据处理。此外,文章还提供了完整的代码示例和配置说明,帮助读者快速掌握相关技能。建议读者参考《尼恩Java面试宝典PDF》进行系统化刷题,提升面试竞争力。关注公众号【技术自由圈】可获取更多技术资源和指导。
|
前端开发
实现Excel文件和其他文件导出为压缩包,并导入
实现Excel文件和其他文件导出为压缩包,并导入
288 1
|
SQL C# 数据库
EPPlus库的安装和使用 C# 中 Excel的导入和导出
本文介绍了如何使用EPPlus库在C#中实现Excel的导入和导出功能。首先,通过NuGet包管理器安装EPPlus库,然后提供了将DataGridView数据导出到Excel的步骤和代码示例,包括将DataGridView转换为DataTable和使用EPPlus将DataTable导出为Excel文件。接着,介绍了如何将Excel数据导入到数据库中,包括读取Excel文件、解析数据、执行SQL插入操作。
EPPlus库的安装和使用 C# 中 Excel的导入和导出
|
前端开发 JavaScript Java
导出excel的两个方式:前端vue+XLSX 导出excel,vue+后端POI 导出excel,并进行分析、比较
这篇文章介绍了使用前端Vue框架结合XLSX库和后端结合Apache POI库导出Excel文件的两种方法,并对比分析了它们的优缺点。
2952 0
|
Java Apache
Apache POI java对excel表格进行操作(读、写) 有代码!!!
文章提供了使用Apache POI库在Java中创建和读取Excel文件的详细代码示例,包括写入数据到Excel和从Excel读取数据的方法。
1907 0
|
存储 关系型数据库 MySQL
Excel 导入 sql3
【7月更文挑战第18天】
207 2
|
Java API Spring
集成EasyPoi(一个基于POI的Excel导入导出工具)到Spring Boot项目中
集成EasyPoi(一个基于POI的Excel导入导出工具)到Spring Boot项目中
1408 1
|
easyexcel Java API
SpringBoot集成EasyExcel 3.x:高效实现Excel数据的优雅导入与导出
SpringBoot集成EasyExcel 3.x:高效实现Excel数据的优雅导入与导出
2907 1
|
关系型数据库 MySQL Windows
MySQL数据导入:MySQL 导入 Excel 文件.md
MySQL数据导入:MySQL 导入 Excel 文件.md