什么是Apache POI?
Apache POI 是一个开源的,用来处理Miscrosoft Office 中如World,Excel,PPT等文件的项目,我们可以在Java程序中通过Apache POI来对Excel文件等进行读写操作,生成报表、数据处理等。当然多使用Apache POI来处理Excel文件。
需要注意:Apache POI 从4.0.1版本开始,需要JDK 8 或更高版本支持。
通过Apache POI操作Excel表格:
导入依赖:(Maven)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
编写方法完成对Excel文件的读写操作
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.time.LocalDateTime;
public class POITest {
public static void main(String[] args) throws Exception {
write();
read();
}
private static void write() throws Exception {
XSSFWorkbook excel = new XSSFWorkbook(); //在内存中创建一个excel文件
XSSFSheet sheet = excel.createSheet("info");//在excel中创建一个 名称为 info 的标签页
XSSFRow row = sheet.createRow(0); //在标签标签页中创建行对象,rownum为第几行,编号从0开始
XSSFCell cell = row.createCell(1); //在行对象中创建单元格,columnIndex编号从0开始
cell.setCellValue("你好"); //在单元格内写入文本内容
row.createCell(2).setCellValue("感谢你阅读我的文章");
row = sheet.createRow(1);
row.createCell(1).setCellValue("时间");
String now = LocalDateTime.now().toString();
row.createCell(2).setCellValue(now);
//通过文件输出流将内存中的excel文件在硬盘中生成
FileOutputStream out = new FileOutputStream("D:/file.xlsx");
excel.write(out);
out.close();
excel.close();
}
private static void read() throws Exception {
FileInputStream input = new FileInputStream("D:/file.xlsx");
XSSFWorkbook excel = new XSSFWorkbook(input); //读取硬盘上指定路径的excel文件
XSSFSheet sheet = excel.getSheetAt(0);//获取excel文件第一个标签页 index序号从0开始
// excel.getSheet("info"); //也可以根据标签名获取标签页
int lastRowNum = sheet.getLastRowNum(); //获取最后一行非空行行号
//遍历循环,从第一行查到最后一行
for (int i = 0; i <= lastRowNum; i++) {
XSSFRow row = sheet.getRow(i);//获得某一行
String rawValue = row.getCell(1).getStringCellValue(); //获取当前行第二个单元格的内容
String rawValue2 = row.getCell(2).getStringCellValue();
System.out.println(rawValue+" "+rawValue2);
}
excel.close();
input.close();
}
}
运行结果截图:
最后,通过Apache POI 也可以对表格的样式进行修改,但多数情况下不会用。如果需要修改样式可以提前准备一个模板Excel文件,然后通过Apache POI进行读写操作生成一个新的Excel文件。