Java poi 导出excel总结
1、认识Excel的两种文件形式:
(1)Excel2003:是特有的二进制格式,核心结构是复核文档类型的结构,存储数量较小
后缀:.xls
(1)Excel2007:核心结构是XML类型的结构,采用的是基于XMl的压缩方式,占用空间小,操作效率高。
后缀:.xls
2、认识POI操作工具
是apache的项目,可对微软的Word,Excel,Ppt进行操作,包括office2003和2007,Excl2003和2007。
3、POI操作Excel的文档结构
(1) HSSF提供读写Microsoft Excel XLS格式档案的功能
(2) XSSF提供读写Microsoft Excel OOXML XLSX格式档案的功能
4、POI的常用API
Workbook: Excel的文档对象,对不同的Excel类型分为:HSSFWorkbook(2003)、XSSFWorkbook(2007)
sheet: Excel的表单
Row: Excel的行
Cell: Excel的格子单元
Font: Excel字体
CellStyle: 格子单元样式
添加的依赖:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-base -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-web -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-annotation -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.0.0</version>
</dependency>
创建Excel案例:
@Test
public void test1() throws Exception {
//1.创建workbook工作簿
Workbook workbook=new XSSFWorkbook();
//2.创建表单Sheet
workbook.createSheet("test1");
//3.文件流
FileOutputStream fileOutputStream=new FileOutputStream("D:\\excel666\\excelTest.xlsx");
//4.写入文件
workbook.write(fileOutputStream);
//5.释放资源
fileOutputStream.close();
}
创建Excel的单元格案例:
@Test
public void test2() throws Exception {
Workbook workbook=new XSSFWorkbook();
Sheet sheet = workbook.createSheet("test1");
// 创建行对象,下标从0开始
Row row = sheet.createRow(2);
//创建单元格,从0开始
Cell cell = row.createCell(1);
//单元格设置内容
cell.setCellValue("导出测试");
FileOutputStream fileOutputStream=new FileOutputStream("D:\\wook666\\excel\\test1.xlsx");
workbook.write(fileOutputStream);
fileOutputStream.close();
}