poi技术
poi技术简介
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件
poi坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
poi结构
HSSF - 提供读写Microsoft Excel XLS格式档案的功能 .xls
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能 .xlsx
HWPF - 提供读写Microsoft Word DOC格式档案的功能
HSLF - 提供读写Microsoft PowerPoint格式档案的功能
HDGF - 提供读Microsoft Visio格式档案的功能
HPBF - 提供读Microsoft Publisher格式档案的功能
HSMF - 提供读Microsoft Outlook格式档案的功能
poi技术入门案例
读取excel文件
@Test
public void readexcel() throws IOException {
// 创建工作表
XSSFWorkbook xssfWorkbook = new XSSFWorkbook("E:\\upload\\学生信息表.xlsx");
// 获取工作簿
XSSFSheet xssfSheet = xssfWorkbook.getSheet("成绩表");
// 获取总行号
int rowtotal = xssfSheet.getLastRowNum();
for(int i=0;i<rowtotal;i++){
XSSFRow row = xssfSheet.getRow(i+1);
System.out.println("学号:"+row.getCell(0).getStringCellValue());
System.out.println("科目编号:"+row.getCell(1).getNumericCellValue());
System.out.println("成绩:"+row.getCell(2).getNumericCellValue());
System.out.println("考试时间:"+row.getCell(3).getStringCellValue());
}
}
写出excel文件
//将数据写入到外部的xlsx文件中
/**
* 写入execl
*/
@Test
public void writeexcel() throws IOException {
// 创建工作表
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
// 创建一个工作簿
XSSFSheet sheet1 = xssfWorkbook.createSheet("offcn");
// 向该工作簿中写数据
XSSFRow row1 = sheet1.createRow(0);
XSSFCell cell1= row1.createCell(0);
cell1.setCellValue("学号");
XSSFCell cell2= row1.createCell(1);
cell2.setCellValue("姓名");
XSSFCell cell3= row1.createCell(2);
cell3.setCellValue("性别");
XSSFCell cell4= row1.createCell(3);
cell4.setCellValue("年龄");
XSSFRow row2 = sheet1.createRow(1);
XSSFCell r2_c1= row2.createCell(0);
r2_c1.setCellValue("s234");
XSSFCell r2_c2= row2.createCell(1);
r2_c2.setCellValue("张三");
XSSFCell r2_c3= row2.createCell(2);
r2_c3.setCellValue("女");
XSSFCell r2_c4= row2.createCell(3);
r2_c4.setCellValue(29);
// excel可以提前不存在
FileOutputStream fileOutputStream = new FileOutputStream("E:\\upload\\offcn.xlsx");
xssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
xssfWorkbook.close();
}