目录
一、Apache POI是什么
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
二、导包
在apache官网下载好后,打开目录是这个样子的,导入这些包
如果是maven项目,可导入maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
三、准备一个导入测试表格
四、编写程序,使用poi导入表格,打印到控制台
@Test
public void excelRead() throws Exception {
//创建输入流,接受目标excel文件
FileInputStream in = new FileInputStream(new File("D:/C盘迁移/Desktop/编程日常/POI导入测试数据.xls"));
//得到POI文件系统对象
POIFSFileSystem fs = new POIFSFileSystem(in);
//得到Excel工作簿对象
HSSFWorkbook wk = new HSSFWorkbook(fs);
//得到Excel工作簿的第一页,即excel工作表对象
HSSFSheet sheet = wk.getSheetAt(0);
//遍历工作表
//遍历行对象
for (Row row : sheet) {
//打印行索引
//System.out.println(row.getRowNum());
//遍历单元格对象
//表头不要打印
for (Cell cell : row) {
//获取每个单元格的类型
int cellType = cell.getCellType();
if(cellType == cell.CELL_TYPE_BLANK){
//System.out.println("空格类型");
System.out.print("\t");
}
if(cellType == cell.CELL_TYPE_NUMERIC){
//System.out.println("数字类型");
System.out.print(cell.getNumericCellValue()+"\t");
}
if(cellType == cell.CELL_TYPE_STRING){
//System.out.println("字符串类型");
System.out.print(cell.getStringCellValue()+"\t");
}
}
//换行
System.out.println();
}
}
跑起来就能看到,我们已经获取了表格的所有数据:
五、使用POI导出表格到磁盘中
@Test
public void excelWrite() throws Exception {
//获得Excel文件输出流
FileOutputStream out = new FileOutputStream(new File("D:/C盘迁移/Desktop/编程日常/POI导出测试数据.xls"));
//创建excel工作簿对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建excel页
HSSFSheet sheet = wb.createSheet("POI导出测试");
//创建表头
HSSFRow row1 = sheet.createRow(0);
//创建表头的单元格-------------------------------
HSSFCell cell1_1 = row1.createCell(0);
cell1_1.setCellValue("学号");
HSSFCell cell1_2 = row1.createCell(1);
cell1_2.setCellValue("姓名");
HSSFCell cell1_3 = row1.createCell(2);
cell1_3.setCellValue("年级");
HSSFCell cell1_4 = row1.createCell(3);
cell1_4.setCellValue("年龄");
HSSFCell cell1_5 = row1.createCell(4);
cell1_5.setCellValue("性别");
//--------------------------------------------
//写入一行内容:
HSSFRow row2 = sheet.createRow(1);
HSSFCell cell2_1 = row2.createCell(0);
cell2_1.setCellValue(1);
HSSFCell cell2_2 = row2.createCell(1);
cell2_2.setCellValue("阿荣");
HSSFCell cell2_3 = row2.createCell(2);
cell2_3.setCellValue("17(3)");
HSSFCell cell2_4 = row2.createCell(3);
cell2_4.setCellValue(20);
HSSFCell cell2_5 = row2.createCell(4);
cell2_5.setCellValue("男");
//输出excel的错误形式:
//out.write(fs.getBytes(), 0, fs.getBytes().length);
//正确形式:
wb.write(out);
//关流
out.close();
}