Apache POl 是一个处理Miscrosoft Ofice各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在Java 程序中对Miscrosoft Office各种文件进行读写操作。
一般情况下,POI都是用于操作 Excel 文件。
一、导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
二、写入excel
//写入
public static void write() throws Exception{
//在内存中创建一个Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
//在Excel文件中创建一个sheet
XSSFSheet sheet = workbook.createSheet("info");
//在sheet中创建行对象,rownum编号从0开始
XSSFRow row = sheet.createRow(0);
//创建单元格并写入文件内容
row.createCell(0).setCellValue("姓名");
row.createCell(1).setCellValue("城市");
//创建一个新的行
XSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("张三");
row1.createCell(1).setCellValue("北京");
//创建一个新的行
XSSFRow row2 = sheet.createRow(2);
row2.createCell(0).setCellValue("李四");
row2.createCell(1).setCellValue("上海");
//通过输出流将workbook对象输出到磁盘
FileOutputStream out = new FileOutputStream(new File("C:\\info.xlsx"));
//关闭资源
workbook.write(out);
out.close();
}
三、读取excel
//读取
public static void read() throws Exception{
FileInputStream fileInputStream = new FileInputStream(new File("C:\\info.xlsx"));
//读取Excel文件
XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
//读取第一个sheet
XSSFSheet sheet = excel.getSheetAt(0);
//获取sheet中的最后一行行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i <= lastRowNum; i++) {
//获取行对象
XSSFRow row = sheet.getRow(i);
//获取单元格对象
String name = row.getCell(0).getStringCellValue();
String city = row.getCell(1).getStringCellValue();
System.out.println(name + " " + city);
}
//关闭资源
excel.close();
fileInputStream.close();
}