Apache POI 基本说明
Apache POI 的可以操作的基本结构
HSSF [1] - 提供读写Microsoft Excel -- XLS格式档案的功能。
XSSF [1] - 提供读写Microsoft Excel OOXML -- XLSX格式档案的功能。
HWPF [1] - 提供读写Microsoft Word -- DOC格式档案的功能。
HSLF [1] - 提供读写Microsoft -- PowerPoint格式档案的功能。
HDGF [1] - 提供读Microsoft -- Visio格式档案的功能。
HPBF [1] - 提供读Microsoft -- Publisher格式档案的功能。
HSMF [1] - 提供读Microsoft -- Outlook格式档案的功能。
在开发中使用POI做什么
1、将用户信息导出为excel表格(导出数据…)
2、将Excel表中的信息录入到网站数据库(习题上传…)大大减轻网站录入量!开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中!
操作Excel目前比较流行的就是Apache POI和阿里巴巴的easyExcel !
图片来自 EasyExcel 文档
POI 是将excel中的数据一次性全部放入内存中
优点︰过程中写入缓存,不操作磁盘,最后一次性写入磁盘,速度快
POI在项目中的操作步骤
- 创建一个普通的maven项目
- 导入pom依赖文件
<dependencies>
<!-- xls03-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!-- xlsx07-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!-- 日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
我们需要知道excel有多少个对象【万物皆对象】我们需要有面向对象的思想,整张表、sheet 、行、列都是对象
我们需要知道excel有03【.xls】版本和07【.xlsx】版本
03版本[.xls] 测试代码
实现遍历65535行账号和密码, 具体实现类是HSSFWorkbook ,记得修改文件输出的路径
private static String path = System.getProperty("user.dir");
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("账户密码信息");
//第一行
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("账户");
Cell cell1 = row.createCell(1);
cell1.setCellValue("密码");
for (int i = 1; i < 65535; i++) {
Row row2 = sheet.createRow(i);
Cell cell2 = row2.createCell(0);
cell2.setCellValue(12345678+i);
Cell cell22 = row2.createCell(1);
cell22.setCellValue(123456+i);
}
FileOutputStream fileOutputStream = new FileOutputStream(path + "\\旧版本账户表.xls"