Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。
需要导入相对应的依赖
<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的使用的代码可读性还是非常的强的,和手动操作excl类似.下面是一个示例代码
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.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class PoiTest {
/**
* 基于POI向Excel文件写入数据
* @throws Exception
*/
public static void write() throws Exception{
//在内存中创建excel对象
XSSFWorkbook excel = new XSSFWorkbook();
//创建sheet页
XSSFSheet sheet = excel.createSheet("mysheet");
//创建行
XSSFRow row1 = sheet.createRow(0);
//在行中创建单元格并且赋值
row1.createCell(0).setCellValue("Name");
row1.createCell(1).setCellValue("Address");
// 创建值行
XSSFRow row2 = sheet.createRow(1);
row2.createCell(0).setCellValue("lingpfeng");
row2.createCell(1).setCellValue("shanghai");
//创建输出流
FileOutputStream out = new FileOutputStream(new File("poi.xls"));
excel.write(out);
out.flush();
out.close();
excel.close();
}
public static void read() throws Exception{
//创建一个输入流
FileInputStream in = new FileInputStream(new File("poi.xls"));
XSSFWorkbook excel = new XSSFWorkbook(in);
XSSFSheet sheet = excel.getSheetAt(0);
XSSFRow row = sheet.getRow(0);
XSSFCell cell = row.getCell(0);
String name = cell.getStringCellValue();
String address = row.getCell(1).getStringCellValue();
System.out.println(name + " " + address);
row = sheet.getRow(1);
cell = row.getCell(0);
name = cell.getStringCellValue();
address = row.getCell(1).getStringCellValue();
System.out.println(name + " " + address);
}
public static void main(String[] args) throws Exception {
write();
read();
}
}