介绍
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件,另外也可使用jxl:专门操作Excel。
使用步骤
1、导入maven坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
2、POI结构
HSSF - 提供读写Microsoft Excel XLS格式档案的功能
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能
HWPF - 提供读写Microsoft Word DOC格式档案的功能
HSLF - 提供读写Microsoft PowerPoint格式档案的功能
HDGF - 提供读Microsoft Visio格式档案的功能
HPBF - 提供读Microsoft Publisher格式档案的功能
HSMF - 提供读Microsoft Outlook格式档案的功能
3、读excel中的数据
@Test
public void test() throws IOException {
//创建工作簿对象
XSSFWorkbook xssf = new XSSFWorkbook(new FileInputStream("/Users/src/test/resources/workbook1.xlsx"));
//读取第一个sheet页
XSSFSheet sheet = xssf.getSheetAt(0);
//遍历sheet页,获取每一行数据
for (Row row : sheet) {
//遍历每一个单元格
System.out.print("---第 "+ row.getRowNum() +" 行:" );
for (Cell cell : row) {
String result = cell.getStringCellValue();
System.out.print(result +" ");
}
System.out.println();
}
xssf.close();
}
4、向excel中写数据
@Test
public void test1() throws IOException {
//创建工作簿对象
XSSFWorkbook xssf = new XSSFWorkbook();
XSSFSheet shet = xssf.createSheet("shet");
XSSFRow row0 = shet.createRow(0);
row0.createCell(0).setCellValue("name");
row0.createCell(1).setCellValue("age");
XSSFRow row1 = shet.createRow(1);
row1.createCell(0).setCellValue("zs");
row1.createCell(1).setCellValue("23");
FileOutputStream out = new FileOutputStream("/Users/wangjian/Documents/code/test_project/itcast_health/health_parent/health_common/src/test/resources/workbook2.xlsx");
out.flush();
xssf.write(out);
xssf.close();
}