广西网站开发,淘宝上做网站权重,东营seo网站推广,沈阳网站建设推广平台POI介绍
Apache POI是用Java编写的免费开源的跨平台的Java API#xff0c;
Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能#xff0c;
其中使用最多的就是使用POI操作Excel文件。
maven坐标#xff1a;
dependencygroupIdorg.apa…POI介绍
Apache POI是用Java编写的免费开源的跨平台的Java API
Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能
其中使用最多的就是使用POI操作Excel文件。
maven坐标
dependencygroupIdorg.apache.poi/groupIdartifactIdpoi/artifactIdversion3.14/version
/dependency
dependencygroupIdorg.apache.poi/groupIdartifactIdpoi-ooxml/artifactIdversion3.14/version
/dependency
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格式档案的功能
入门案例
从Excel文件读取数据
使用POI可以从一个已经存在的Excel文件中读取数据 public class POITest {//使用POI读取Excel中的数据Testpublic void test1() throws Exception {//加载指定文件创建一个Excel工作簿XSSFWorkbook excel new XSSFWorkbook(new FileInputStream(new File(C:\\poitest.xlsx)));//读取Excel文件中第一个sheet标签项XSSFSheet sheet excel.getSheetAt(0);//遍历sheet标签项获取每一行数据for (Row row : sheet) {//遍历行获取每个单元对象for (Cell cell : row) {System.out.println(cell.getStringCellValue());}}//关闭资源excel.close();}Testpublic void test2() throws Exception {//加载指定文件创建一个Excel工作簿XSSFWorkbook excel new XSSFWorkbook(new FileInputStream(new File(C:\\poitest.xlsx)));//读取Excel文件中第一个sheet标签项XSSFSheet sheet excel.getSheetAt(0);//获取当前工作表最后一行的行号行号从0开始int lastRowNum sheet.getLastRowNum();for(int i0;ilastRowNum;i){//根据行号获取行对象XSSFRow row sheet.getRow(i);//获取当前行的最后一个单元格索引short lastCellNum row.getLastCellNum();for(short j0;jlastCellNum;j){//根据单元格索引获得单元格对象XSSFCell cell row.getCell(j);System.out.println(cell.getStringCellValue());}}//关闭资源excel.close();}
}
XSSFWorkbook工作簿
XSSFSheet工作表
Row行
Cell单元格
向Excel文件写入数据 public class POITest {//使用POI向Excel文件写入数据并且通过输出流将创建的Excel文件保存到本地磁盘Testpublic void test3() throws Exception{//在内存中创建一个Excel文件工作簿XSSFWorkbook excel new XSSFWorkbook();//创建一个工作表对象XSSFSheet sheet excel.createSheet(POI写入数据);//在工作表中创建行对象XSSFRow title sheet.createRow(0);//在行中创建单元格对象title.createCell(0).setCellValue(姓名);title.createCell(1).setCellValue(地址);title.createCell(2).setCellValue(年龄);XSSFRow dataRow sheet.createRow(1);//在行中创建单元格对象dataRow.createCell(0).setCellValue(小明);dataRow.createCell(1).setCellValue(广州);dataRow.createCell(2).setCellValue(20);//创建一个输出流通过输出流将内存中的Excel文件写入本地磁盘FileOutputStream outputStream new FileOutputStream(C:\\hello1.xlsx);excel.write(outputStream);outputStream.flush();excel.close();}
}