下饶网站建设,网店推广实训系统,远离有害不良网站应该怎么做,东莞市 住房与城乡建设部网站三十二、Apache POI
32.1 介绍
Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是#xff0c;我们可以使用POI在Java程序中对Miscrosoft Office各种文件进行读写操作。
一般情况下#xff0c;POI都是用于操作Excel文件。
Apache POI 的应用场…三十二、Apache POI
32.1 介绍
Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是我们可以使用POI在Java程序中对Miscrosoft Office各种文件进行读写操作。
一般情况下POI都是用于操作Excel文件。
Apache POI 的应用场景 银行网银系统导出交易明细 各种业务系统导出Excel报表 批量导入业务数据
32.2 入门案例
Apache POI 既可以将数据写入Excel文件也可以读取Excel文件中的数据接下来分别进行实现。
Apache POI的maven坐标
dependencygroupIdorg.apache.poi/groupIdartifactIdpoi/artifactIdversion3.16/version
/dependency
dependencygroupIdorg.apache.poi/groupIdartifactIdpoi-ooxml/artifactIdversion3.16/version
/dependency32.2.1 将数据写入Excel文件
1). 代码开发
package com.sky.test;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.FileNotFoundException;
import java.io.FileOutputStream;public class POITest {/*** 通过POI创建Excel 文件并且写入文件内容*/public static void write() throws Exception {//在内存中创建一个Excel文件XSSFWorkbook excel new XSSFWorkbook();//在Excel文件中创建一个Sheet页XSSFSheet sheet excel.createSheet(info);//在Sheet中创建一个行对象,rownum编号从0开始XSSFRow row sheet.createRow(0);//创建单元格并且写入文件内容row.createCell(0).setCellValue(姓名);row.createCell(1).setCellValue(城市);//创建一个新行row sheet.createRow(1);row.createCell(0).setCellValue(张三);row.createCell(1).setCellValue(北京);row sheet.createRow(2);row.createCell(0).setCellValue(李四);row.createCell(1).setCellValue(南京);//通过输出流将内存中的Excel文件写入到磁盘FileOutputStream out new FileOutputStream(new File(D:\\info.xlsx));excel.write(out);//关闭资源out.close();excel.close();}public static void main(String[] args) throws Exception {write();}
}
2). 实现效果
在D盘中生成info.xlsx文件创建名称为info的Sheet页同时将内容成功写入。 32.2.2 读取Excel文件中的数据
1). 代码开发
/*** 通过POI读取Excel文件中的内容*/
public static void read() throws Exception {InputStream inputStream new FileInputStream(new File(D:\\info.xlsx));//读取磁盘上已经存在的Excel文件XSSFWorkbook excel new XSSFWorkbook(inputStream);//读取Excel文件中的第一个Sheet页XSSFSheet sheet excel.getSheetAt(0);//获取Sheet中最后一行的行号int lastRowNum sheet.getLastRowNum();for (int i0;ilastRowNum;i){//获得某一行XSSFRow row sheet.getRow(i);//获得单元格对象String cellValue1 row.getCell(0).getStringCellValue();String cellValue2 row.getCell(1).getStringCellValue();System.out.println(cellValue1 cellValue2);}//关闭资源inputStream.close();excel.close();
}public static void main(String[] args) throws Exception {//write();read();
}2). 实现效果