<!--POI-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
  • ExcelAttribute:
/**
* 自定义注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttribute {
//对应的列名称
String name() default ""; // default java8新特性
//列序号
int sort();
//字段类型对应的格式
String format() default "";
}
  • ExcelExportUtil:
/**
* 导出
*/
@Getter
@Setter
public class ExcelExportUtil<T> { private int rowIndex;
private int styleIndex;
private String templatePath;
private Class clazz;
private Field fields[]; public ExcelExportUtil(Class clazz,int rowIndex,int styleIndex) {
this.clazz = clazz;
this.rowIndex = rowIndex;
this.styleIndex = styleIndex;
fields = clazz.getDeclaredFields();//获取声明字段
} /**
* 基于注解导出
*/
public void export(HttpServletResponse response,InputStream is, List<T> objs,String fileName) throws Exception { XSSFWorkbook workbook = new XSSFWorkbook(is);
Sheet sheet = workbook.getSheetAt(0); CellStyle[] styles = getTemplateStyles(sheet.getRow(styleIndex)); AtomicInteger datasAi = new AtomicInteger(rowIndex);
for (T t : objs) {
Row row = sheet.createRow(datasAi.getAndIncrement());
for(int i=0;i<styles.length;i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(styles[i]);
for (Field field : fields) {
if(field.isAnnotationPresent(ExcelAttribute.class)){
field.setAccessible(true);
ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
if(i == ea.sort()) { //列序号
cell.setCellValue(field.get(t).toString());
}
}
}
}
}
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("ISO8859-1")));
response.setHeader("filename", fileName);
workbook.write(response.getOutputStream());
} public CellStyle[] getTemplateStyles(Row row) {
CellStyle [] styles = new CellStyle[row.getLastCellNum()];
for(int i=0;i<row.getLastCellNum();i++) {
styles[i] = row.getCell(i).getCellStyle();
}
return styles;
}
}
  • ExcelImportUtil:

public class ExcelImportUtil<T> { private Class clazz;
private Field fields[]; public ExcelImportUtil(Class clazz) {
this.clazz = clazz;
fields = clazz.getDeclaredFields();
} /**
* 基于注解读取excel
*/
public List<T> readExcel(InputStream is, int rowIndex,int cellIndex) {
List<T> list = new ArrayList<T>();
T entity = null;
try {
XSSFWorkbook workbook = new XSSFWorkbook(is);
Sheet sheet = workbook.getSheetAt(0);
// 不准确
int rowLength = sheet.getLastRowNum(); System.out.println(sheet.getLastRowNum());
for (int rowNum = rowIndex; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
entity = (T) clazz.newInstance();
System.out.println(row.getLastCellNum());
for (int j = cellIndex; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
for (Field field : fields) {
if(field.isAnnotationPresent(ExcelAttribute.class)){
field.setAccessible(true);
ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
if(j == ea.sort()) {
field.set(entity, covertAttrType(field, cell));
}
}
}
}
list.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
} /**
* 类型转换 将cell 单元格格式转为 字段类型
*/
private Object covertAttrType(Field field, Cell cell) throws Exception {
String fieldType = field.getType().getSimpleName();
if ("String".equals(fieldType)) {
return getValue(cell);
}else if ("Date".equals(fieldType)) {
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(getValue(cell)) ;
}else if ("int".equals(fieldType) || "Integer".equals(fieldType)) {
return Integer.parseInt(getValue(cell));
}else if ("double".equals(fieldType) || "Double".equals(fieldType)) {
return Double.parseDouble(getValue(cell));
}else {
return null;
}
} /**
* 格式转为String
* @param cell
* @return
*/
public String getValue(Cell cell) {
if (cell == null) {
return "";
}
switch (cell.getCellType()) {
case STRING:
return cell.getRichStringCellValue().getString().trim();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
Date dt = DateUtil.getJavaDate(cell.getNumericCellValue());
return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dt);
} else {
// 防止数值变成科学计数法
String strCell = "";
Double num = cell.getNumericCellValue();
BigDecimal bd = new BigDecimal(num.toString());
if (bd != null) {
strCell = bd.toPlainString();
}
// 去除 浮点型 自动加的 .0
if (strCell.endsWith(".0")) {
strCell = strCell.substring(0, strCell.indexOf("."));
}
return strCell;
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return "";
}
}
}
  • 注解实例:
    @ExcelAttribute(sort = 0)
private String userId;
@ExcelAttribute(sort = 1)
private String username;
  • 导出实例:
        //加载模板流数据
Resource resource = new ClassPathResource("excel-template/hr-demo.xlsx");
FileInputStream fis = new FileInputStream(resource.getFile());
new ExcelExportUtil(PoiEmployeeReportResult.class,2,2).export(response,fis,list,"报表.xlsx");
  • 导入实例:
   List list = new ExcelImportUtil(User.class).readExcel(file.getInputStream(), 1, 0);

poi 工具类的更多相关文章

  1. 关于Excel导入导出POI工具类

    import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import ...

  2. Apache POI 工具类 [ PoiUtil ]

    pom.xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml ...

  3. Java操作Excel工具类(poi)

    分享一个自己做的poi工具类,写不是很完全,足够我自己当前使用,有兴趣的可以自行扩展 1 import org.apache.commons.lang3.exception.ExceptionUtil ...

  4. excel导出工具类

    package com.jianwu.util.excel; import com.google.common.collect.Lists;import com.jianwu.exception.Mo ...

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

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

  6. 导入导出封装的工具类 (一) 利用POI封装

    对于导入导出各个项目中差点儿都会用到,记得在高校平台中封装过导入导出这部分今天看了看是利用JXL封装的而经理说让我用POI写写导出,这两个导入导出框架是眼下比較流程和经常使用的框架,有必要都了解一下. ...

  7. 使用POI插件,提取导出excel的工具类

    在网站的不同的模块都需要使用到导入导出excel的功能,我们就需要写一个通用的工具类ExcelUtil. 我的思路:首先,导入和导出的Excel的文件格式固定:主标题,二级标题,数据行(姑且就这么叫) ...

  8. 一个基于POI的通用excel导入导出工具类的简单实现及使用方法

    前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...

  9. POI读取excel工具类 返回实体bean集合(xls,xlsx通用)

    本文举个简单的实例 读取上图的 excel文件到 List<User>集合 首先 导入POi 相关 jar包 在pom.xml 加入 <!-- poi --> <depe ...

随机推荐

  1. Judy Beta 第二天

    Intro 我们采取的code review方式是两人一组,每个人在自己的分支上完成工作后向master分支发起pull request,小组的另一人对pr进行review后merge进入原仓库.gi ...

  2. 理解UDP协议的首部校验和校验和

    reference: https://blog.csdn.net/qiuchangyong/article/details/79945630 https://seanwangjs.github.io/ ...

  3. 常见的操作系统及linux发展史

    目前我们常见的操作系统有: 1> 桌面操作系统 Windows 系列 用户群体大 macOS 适合于开发人员 Linux 应用软件少 2> 服务器操作系统 Linux 安全.稳定.免费 占 ...

  4. vue axios上传文件实例

    <head> <title></title> <meta charset="UTF-8"> <meta name=" ...

  5. 2018-2019-2 20175224 实验二《Java面向对象程序设计》实验报告

    一.实验报告封面 课程:Java程序设计 班级:1752班 姓名:艾星言 学号:20175224 指导教师:娄嘉鹏 实验日期:2019年4月17日 实验时间:13:45 - 15:25 实验序号:24 ...

  6. shell中特殊位置参数变量

    shell中特殊位置参数变量:$0.$n.$#.$*.$@ $0:获取当前执行shell脚本文件名,如果执行脚本包含路径,那么就包括脚本路径 $n:获取当前执行shell脚本的第n个参数值.n=1.. ...

  7. Java复数的加乘除运算

    //主要是对零的处理,有什么不对的地方欢迎批评指正,一起进步class complex{ double a,b; public String toString() { return("实部: ...

  8. 设置Linux系统的LANG变量

    设置linux系统的LANG变量 对于国内的Linux用户,经常烦恼的一个问题是:系统常常在需要显示中文的时候却显示成了乱码,而由于某些原因,需要英文界面的系统的时候,却苦于系统不能正常输入和显示中文 ...

  9. loadrunner11浏览器兼容性的问题

    最近项目中遇到了新开发的系统,全是HTML5和一些最新的前端框架技术,由于没有做浏览器兼容处理,所以该系统无法在IE浏览器进行操作,对firefox和google浏览器支持较好.但是又一个问题出现了, ...

  10. 深度学习(PYTORCH)-3.sphereface-pytorch.lfw_eval.py详解

    pytorch版本sphereface的原作者地址:https://github.com/clcarwin/sphereface_pytorch 由于接触深度学习不久,所以花了较长时间来阅读源码,以下 ...