通过Excel认识POI
1、POI是什么
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format.
XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format.
XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
2、POI核心类
2.1 工作簿 Workbook
- HSSFWorkbook : 有读取.xls 格式和写入Microsoft Excel文件的方法。它与微软Office97-2003版本兼容
- XSSFWorkbook : 有读写Microsoft Excel和OpenOffice的XML文件的格式.xls或.xlsx的方法。它与MS-Office版本2007或更高版本兼容
//直接创建新的
HSSFWorkbook()
//通过输入流创建
HSSFWorkbook(java.io.InputStream s)//直接创建新的
HSSFWorkbook()
//通过输入流创建
HSSFWorkbook(java.io.InputStream s)
//直接创建新的
XSSFWorkbook()
//通过File类创建
XSSFWorkbook(java.io.File file)
//通过输入流创建
XSSFWorkbook(java.io.InputStream is)//直接创建新的
XSSFWorkbook()
//通过File类创建
XSSFWorkbook(java.io.File file)
//通过输入流创建
XSSFWorkbook(java.io.InputStream is)
2.2 标签页 Sheet
workbook.createSheet();
workbook.createSheet(String sheetName);workbook.createSheet();
workbook.createSheet(String sheetName);
2.3 行 Row
sheet.createRow(int rownum);sheet.createRow(int rownum);
2.4 单元格 Cell
row.createCell(int column);
row.createCell(int column, int type);row.createCell(int column);
row.createCell(int column, int type);
3、创建和读取
3.1 创建空白工作簿
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class CreateWorkBook
{
   public static void main(String[] args)throws Exception
   {
      //Create Blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook();
      //Create file system using specific name
      FileOutputStream out = new FileOutputStream(
      new File("createworkbook.xlsx"));
      //write operation workbook using file out object
      workbook.write(out);
      out.close();
      System.out.println("
      createworkbook.xlsx written successfully");
   }
}import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class CreateWorkBook
{
public static void main(String[] args)throws Exception
   {
//Create Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create file system using specific name
FileOutputStream out = new FileOutputStream(
      new File("createworkbook.xlsx"));
//write operation workbook using file out object
workbook.write(out);
out.close();
      System.out.println("
createworkbook.xlsx written successfully");
}
}
3.2 打开现有的工作簿
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class OpenWorkBook
{
   public static void main(String args[])throws Exception
   {
      File file = new File("openworkbook.xlsx");
      FileInputStream fIP = new FileInputStream(file);
      //Get the workbook instance for XLSX file
      XSSFWorkbook workbook = new XSSFWorkbook(fIP);
      if(file.isFile() && file.exists())
      {
         System.out.println(
         "openworkbook.xlsx file open successfully.");
      }
      else
      {
         System.out.println(
         "Error to open openworkbook.xlsx file.");
      }
   }
}import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class OpenWorkBook
{
public static void main(String args[])throws Exception
   { 
      File file = new File("openworkbook.xlsx");
FileInputStream fIP = new FileInputStream(file);
//Get the workbook instance for XLSX file
XSSFWorkbook workbook = new XSSFWorkbook(fIP);
if(file.isFile() && file.exists())
      {
System.out.println(
"openworkbook.xlsx file open successfully.");
}
else
      {
System.out.println(
"Error to open openworkbook.xlsx file.");
}
}
}
4、方法示例:任意对象List转至为Excel文档(可用注解定义标签名和列名)
@Excel(name = "学生标签页")
public class Student {
    @Excel(name = "姓名")
    private String name;
    private boolean male;
    @Excel(name = "身高")
    private int height;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public boolean isMale() {
        return male;
    }
    public void setMale(boolean male) {
        this.male = male;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
}@Excel(name = "学生标签页")
public class Student {
@Excel(name = "姓名")
private String name;
private boolean male;
@Excel(name = "身高")
private int height;
    public String getName() {
return name;
}
    public void setName(String name) {
this.name = name;
}
    public boolean isMale() {
return male;
}
    public void setMale(boolean male) {
this.male = male;
}
    public int getHeight() {
return height;
}
    public void setHeight(int height) {
this.height = height;
}
}
public static void main(String[] args) {
    List<Student> list = new ArrayList<Student>();
    Student student1 = new Student();
    student1.setName("小红");
    student1.setMale(false);
    student1.setHeight(167);
    Student student2 = new Student();
    student2.setName("小明");
    student2.setMale(true);
    student2.setHeight(185);
    list.add(student1);
    list.add(student2);
    File file = new File("C:/Users/Dulk/Desktop/1314.xls");
    createExcel(list, file);
}public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student student1 = new Student();
    student1.setName("小红");
student1.setMale(false);
student1.setHeight(167);
Student student2 = new Student();
    student2.setName("小明");
student2.setMale(true);
student2.setHeight(185);
list.add(student1);
list.add(student2);
    File file = new File("C:/Users/Dulk/Desktop/1314.xls");
createExcel(list, file);
}

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Excel {
    //设置名称
    public String name() default "";
}import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Excel {
//设置名称
public String name() default "";
}
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
 * Excel的操作工具类
 */
public class ExcelUtil {
    private static Logger log = Logger.getLogger(ExcelUtil.class);
    /**
     * 获取某个File文件对应的Workbook工作簿对象
     */
    public static Workbook gainWorkbook(File file) throws ExcelException {
        if (!isExcel(file)) {
            throw new ExcelException("文件不是Excel类型");
        }
        //如果文件不存在则新建
        if (!file.exists()) {
            try {
                OutputStream os = new FileOutputStream(file);
                Workbook workbook = isOlderEdition(file) ? new HSSFWorkbook() : new XSSFWorkbook();
                workbook.write(os);
                log.debug("文件不存在,新建该Excel文件");
                os.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            InputStream is = new FileInputStream(file);
            return isOlderEdition(file) ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 判断某个Excel文件是否是2003-2007通用旧版
     */
    private static boolean isOlderEdition(File file) {
        return file.getName().matches(".+\\.(?i)xls");
    }
    /**
     * 判断文件是否是一个Excel文件
     */
    private static boolean isExcel(File file) {
        String fileName = file.getName();
        String regXls = ".+\\.(?i)xls";
        String regXlsx = ".+\\.(?i)xlsx";
        return fileName.matches(regXls) || fileName.matches(regXlsx);
    }
    /**
     * 将某个对象的List转换为Excel工作簿
     */
    public static <E> Workbook createExcel(List<E> list, File file) {
        String sheetName = "default";
        if (list.size() == 0) {
            return null;
        }
        Workbook workbook = null;
        try {
            Class clazz = list.get(0).getClass();
            Field[] fields = clazz.getDeclaredFields();
            if (clazz.isAnnotationPresent(Excel.class)) {
                Excel excel = (Excel) clazz.getAnnotation(Excel.class);
                sheetName = excel.name();
            }
            workbook = gainWorkbook(file);
            Sheet sheet = workbook.createSheet(sheetName);
            //创建首行
            Row line = sheet.createRow(0);
            for (int k = 0; k < fields.length; k++) {
                Cell cell = line.createCell(k);
                String columnName = fields[k].getName();
                if (fields[k].isAnnotationPresent(Excel.class)) {
                    Excel excel = fields[k].getAnnotation(Excel.class);
                    columnName = excel.name();
                }
                cell.setCellValue(columnName);
            }
            //创建数据
            for (int i = 1; i <= list.size(); i++) {
                Row row = sheet.createRow(i);
                for (int j = 1; j <= fields.length; j++) {
                    Cell cell = row.createCell(j - 1);
                    String fieldName = fields[j - 1].getName();
                    String fieldFirstLetterUpper = fieldName.substring(0, 1).toUpperCase();
                    String prefix = "get";
                    if ("boolean".equals(fields[j - 1].getType().getName())) {
                        prefix = "is";
                    }
                    String methodName = prefix + fieldFirstLetterUpper + fieldName.substring(1);
                    Method method = clazz.getMethod(methodName);
                    cell.setCellValue(String.valueOf(method.invoke(list.get(i - 1))));
                }
            }
            log.debug("List读入完毕");
            OutputStream os = new FileOutputStream(file);
            workbook.write(os);
            os.close();
        } catch (ExcelException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }
}import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Excel的操作工具类
*/
public class ExcelUtil {
private static Logger log = Logger.getLogger(ExcelUtil.class);
/**
* 获取某个File文件对应的Workbook工作簿对象
*/
    public static Workbook gainWorkbook(File file) throws ExcelException {
        if (!isExcel(file)) {
            throw new ExcelException("文件不是Excel类型");
}
//如果文件不存在则新建
        if (!file.exists()) {
            try {
OutputStream os = new FileOutputStream(file);
Workbook workbook = isOlderEdition(file) ? new HSSFWorkbook() : new XSSFWorkbook();
workbook.write(os);
                log.debug("文件不存在,新建该Excel文件");
os.close();
            } catch (FileNotFoundException e) {
e.printStackTrace();
            } catch (IOException e) {
e.printStackTrace();
}
}
        try {
InputStream is = new FileInputStream(file);
return isOlderEdition(file) ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
        } catch (FileNotFoundException e) {
e.printStackTrace();
        } catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 判断某个Excel文件是否是2003-2007通用旧版
*/
    private static boolean isOlderEdition(File file) {
        return file.getName().matches(".+\\.(?i)xls");
}
/**
* 判断文件是否是一个Excel文件
*/
    private static boolean isExcel(File file) {
String fileName = file.getName();
String regXls = ".+\\.(?i)xls";
String regXlsx = ".+\\.(?i)xlsx";
return fileName.matches(regXls) || fileName.matches(regXlsx);
}
/**
* 将某个对象的List转换为Excel工作簿
*/
    public static <E> Workbook createExcel(List<E> list, File file) {
String sheetName = "default";
        if (list.size() == 0) {
return null;
}
Workbook workbook = null;
        try {
Class clazz = list.get(0).getClass();
Field[] fields = clazz.getDeclaredFields();
            if (clazz.isAnnotationPresent(Excel.class)) {
Excel excel = (Excel) clazz.getAnnotation(Excel.class);
sheetName = excel.name();
}
workbook = gainWorkbook(file);
Sheet sheet = workbook.createSheet(sheetName);
//创建首行
Row line = sheet.createRow(0);
            for (int k = 0; k < fields.length; k++) {
Cell cell = line.createCell(k);
String columnName = fields[k].getName();
                if (fields[k].isAnnotationPresent(Excel.class)) {
Excel excel = fields[k].getAnnotation(Excel.class);
columnName = excel.name();
}
cell.setCellValue(columnName);
}
//创建数据
            for (int i = 1; i <= list.size(); i++) {
Row row = sheet.createRow(i);
                for (int j = 1; j <= fields.length; j++) {
Cell cell = row.createCell(j - 1);
String fieldName = fields[j - 1].getName();
String fieldFirstLetterUpper = fieldName.substring(0, 1).toUpperCase();
String prefix = "get";
                    if ("boolean".equals(fields[j - 1].getType().getName())) {
prefix = "is";
}
String methodName = prefix + fieldFirstLetterUpper + fieldName.substring(1);
Method method = clazz.getMethod(methodName);
cell.setCellValue(String.valueOf(method.invoke(list.get(i - 1))));
}
}
            log.debug("List读入完毕");
OutputStream os = new FileOutputStream(file);
workbook.write(os);
os.close();
        } catch (ExcelException e) {
e.printStackTrace();
        } catch (InvocationTargetException e) {
e.printStackTrace();
        } catch (NoSuchMethodException e) {
e.printStackTrace();
        } catch (IllegalAccessException e) {
e.printStackTrace();
        } catch (FileNotFoundException e) {
e.printStackTrace();
        } catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
}
5、参考链接
通过Excel认识POI的更多相关文章
- java写入excel文件poi
		java写入excel文件 java写入excel文件poi,支持xlsx与xls,没有文件自动创建 package com.utils; import java.io.File; import ja ... 
- 一脸懵逼学习Java操作Excel之POI(Apache POI)
		Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 1:下面简单的程序来创建一个空白Microsoft ... 
- Excel的poi缓存问题
		Excel的poi缓存问题 背景: 最近工作需要,需要完成生成新的Excel,然后从Excel中读取包含公式的文本内容. 问题: 当程序中修改公式对应的单元格数据变化时,公式获取的值仍然还是原来的值, ... 
- java操作excel总结---poi
		前不久做过Excel的导入导出功能,其主要的难点是java如何操作Excel文档.现在就来介绍一下利用Apache的poi如何操作Excel. 1.准备工作:导入Apache POI的相关jar包,P ... 
- Java 实现导出excel表 POI
		1.首先下载poi-3.6-20091214.jar 2.Student.java import java.util.Date; public class Student { private int ... 
- flex+java将数据库里的数据导出到指定目录下excel表里(poi)
		数据写入到excel中采用的是Apache POI: //java后台的一个工具类(该工具类适用于为不同字段添加,方便) /* 下面这个方法是将list转换为Excel工作表的 */ public s ... 
- Java 操作Excel 之Poi(第一讲)
		1.Poi 简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能.HSSF - 提供读写Micros ... 
- springMVC导入excel案例poi
		直接上代码: 第一步,controller 引入 private static final String CHECK_FILE = "checkExceFile"; /** * 对 ... 
- importExcel运用注解实现EXCEL导入poi类
		JAVA报表 package com.app.common.excel; import java.io.File; import java.io.FileInputStream; import jav ... 
- C++读写EXCEL文件OLE,java读写excel文件POI 对比
		C++读写EXCEL文件方式比较 有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看.http://www.cnblogs.com/destim/p/5476915.html C++ ... 
随机推荐
- JavaWeb三大组件之一Filter知识总结
			[1] Filter简介 > Filter翻译为中文是过滤器的意思. > Filter是JavaWeb的三大web组件之一Servlet.Filter.Listener ... 
- 一些方便的bash命令
			1.文件名大小写转换: (1)大写转小写: ls | awk '{printf("mv %s %s\n", $0, tolower($0))|"sh"}' (2 ... 
- postman进行http接口测试
			HTTP的接口测试工具有很多,可以进行http请求的方式也有很多,但是可以直接拿来就用,而且功能还支持的不错的,我使用过的来讲,还是postman比较上手. 优点: 1.支持用例管理 2.支持get. ... 
- Mybatis分页插件PageHelper正确的使用方法(网上有2篇不够科学的文章)
			今天下午在Mybatis项目中,实现分页.因为我是后加入项目中的,Leader用的是PageHelper这个组件,但是我在实际使用的过程中遇到了2个大问题. 1.http://www.oschina. ... 
- Dynamics 365中部分账号使用系统明显缓慢怎么办?先这么干!
			摘要: 本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复263或者20170828可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyon ... 
- java web面试技巧,数据库面试,java web轻量级开发面试教程
			我最近看到一本比较好的讲java web方面面试的书,java web轻量级开发面试教程. 其中不仅用案例和视频讲述了Spring MVC,Hibernate, ORM等方面的技巧,而且还实际讲到了面 ... 
- python-opencv在有噪音的情况下提取图像的轮廓
			对于一般的图像提取轮廓,这篇博文介绍了一个很好的方法,但是对于有噪声的图像,并不能很好地捕获到目标物体. 比如对于我的鼠标,提取的轮廓效果并不好,因为噪声很多: 所以本文增加了去掉噪声的部分. 首先加 ... 
- js实现每次程序发送一个数据 ,多次发送不一样,5秒后继续执行多次程序,判断如果五秒后发送过来的数据和上次不一样,少的删除多的增加
			/*存储设备ID*/var IDSNew = new Array();//判断是否已经启用服务var isopen = true;//需要放到接收设备数据处IDSNew[client.deviceId ... 
- 【拦截器】HandlerInterceptor接口
			package org.springframework.web.servlet; import javax.servlet.http.HttpServletRequest; import javax. ... 
- Spring框架Controller层(表现层)针对方法参数是Bean时HttpServletRequest绑定参数值问题解释
			在做项目的时候,有一个需求是将数据库中的信息封装到实体类返回到jsp界面 传过来的参数只是实体类的id属性,然后根据id属性去查数据库,事情就是这样,然后 结果遇到很奇怪的事情,在jsp页面中使用EL ... 
