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全版本通用代码
public class PoiExcelWritelProcess {
public static void main(String
[] args
) throws IOException
{
File file
= new File("test/helloworld.xlsx");
OutputStream outputStream
= new FileOutputStream(file
);
Workbook workbook
= getWorkBook(file
);
Sheet sheet
= workbook
.createSheet("Sheet1");
Row row
= sheet
.createRow(0);
row
.createCell(0).setCellValue("post_id");
row
.createCell(1).setCellValue("post_title");
for (int i
= 0; i
< 2; i
++) {
Row everyRow
= sheet
.createRow(i
+ 1);
everyRow
.createCell(0).setCellValue("帖子id为:0" + i
);
everyRow
.createCell(1).setCellValue("帖子内容为:" + i
);
}
workbook
.write(outputStream
);
workbook
.close();
outputStream
.close();
}
public static Workbook
getWorkBook(File file
) {
Workbook workbook
= null
;
if(file
.getName().endsWith("xls")){
workbook
= new HSSFWorkbook();
}
else if (file
.getName().endsWith("xlsx")){
workbook
= new XSSFWorkbook();
}
return workbook
;
}
}
Java读取Excel全版本通用代码
public class PoiExcelRead {
public static void main(String
[] args
) throws IOException
{
File file
= new File("test/helloworld.xlsx");
Workbook workbook
= getWorkBook(file
);
Sheet sheet
= workbook
.getSheet("Sheet1");
int allRow
= sheet
.getLastRowNum();
for (int i
= 0; i
<= allRow
; i
++) {
Row row
= sheet
.getRow(i
);
short lastCellNum
= row
.getLastCellNum();
for (int j
= 0; j
< lastCellNum
; j
++) {
String cellValue
= row
.getCell(j
).getStringCellValue();
System
.out
.print(cellValue
+ "\t");
}
System
.out
.println();
}
workbook
.close();
}
public static Workbook
getWorkBook(File file
) throws IOException
{
InputStream in
= new FileInputStream(file
);
Workbook workbook
= null
;
if(file
.getName().endsWith("xls")){
workbook
= new HSSFWorkbook(in
);
}
else if (file
.getName().endsWith("xlsx")){
workbook
= new XSSFWorkbook(in
);
}
in
.close();
return workbook
;
}
}
运行结果