POI是Java编写的开源跨平台Excel处理工具,不仅提供了对Excel的操作,也提供了对Word、PowerPoint和Visio等格式的文档的操作。
jar包下载
基于Maven工程的pom.xml文件配置POI如下所示:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
相关类的介绍
Workbook:Workbook接口,用于创建工作簿。
Sheet:Sheet接口,用于创建工作表。
Row:Row接口,用于操作行。
Cell:Cell接口,用于操作列。
针对xls格式的Excel数据,需要使用HSSF开头的类进行操作;针对xlsx格式(Excel 2007以上版本)的Excel数据,需要使用XSSF开头的类进行操作。
相关方法的介绍
createRow(int column)方法:创建某行。
createCell(int column)方法:创建某列。
setCellValue(String value)方法:为该单元格赋值。
getSheet(String name)方法:读取工作表。
getSheetAt(int index)方法:读取工作表。
getLastRowNum()方法:获取表格的所有行数。
getLastCellNum()方法:获取某行的所有列数。
Java写入Excel全版本通用代码
/**
* 使用POI写入Excel(包括xls和xlsx)
*
* @author hakutaku
* @create 2020-07-01-21:07
**/
public class PoiExcelWritelProcess {
public static void main(String[] args) throws IOException {
// 文件名称
File file = new File("test/helloworld.xlsx");
// File file = new File("test/read.xlsx");
OutputStream outputStream = new FileOutputStream(file);
Workbook workbook = getWorkBook(file);
Sheet sheet = workbook.createSheet("Sheet1");
// 添加表头
Row row = sheet.createRow(0)