Apache POI
- Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以用POI在JAVA程序中对Miscrosoft Office各种文件进行读写操作。一般情况,POI都是用以操作Excel文件。
写操作
@SpringBootTest
public class POITest {
public static void write() throws IOException {
XSSFWorkbook excel=new XSSFWorkbook();
XSSFSheet sheet=excel.createSheet("info");
XSSFRow row=sheet.createRow(1);
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("城市");
row=sheet.createRow(2);
row.createCell(1).setCellValue("张三");
row.createCell(2).setCellValue("北京");
row=sheet.createRow(3);
row.createCell(1).setCellValue("李四");
row.createCell(2).setCellValue("南京");
FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\info.xlsx"));
excel.write(fileOutputStream);
fileOutputStream.close();
excel.close();
}
public static void main(String[] args) throws IOException {
write();
}
}
写操作
public static void read() throws Exception{
FileInputStream stream = new FileInputStream(new File("D:\\info.xlsx"));
XSSFWorkbook excel=new XSSFWorkbook(stream);
XSSFSheet sheetAt = excel.getSheetAt(0);
int lastRowNum = sheetAt.getLastRowNum();
for(int i=1;i<=lastRowNum;i++){
XSSFRow row = sheetAt.getRow(i);
String value1 = row.getCell(1).getStringCellValue();
String value2 = row.getCell(2).getStringCellValue();
System.out.println(value1+" "+value2);
}
stream.close();
excel.close();
}