今天学习了Excel数据的写入和读取,这里做下记录
参考网址
POI介绍
POI是Apache软件基金会用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
所以POI的主要功能是可以用Java操作Microsoft Office的相关文件,但是一般我们都是用来操作Excel相关文件。
使用前提
添加依赖
<!--POI报表-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
注意:
操作Excel文件区分版本:
2003版本(包含2003)以前的扩展名为.xls需要用HSSFWorkbook类操作
2007版本(包含2007)以后的扩展名为.xlsx需要用XSSFWorkbook类操作
这里我是用的是2007版本
代码实现
读取文件数据
/**
* 使用POI读取Excel文件数据
*/
@Test
public void read() throws IOException {
//1.使用流读取文件 --文件路径自己更改
FileInputStream inputStream =
new FileInputStream(new File("C:\\Users\\hp\\Desktop\\aaaaa.xlsx"));
//2.使用xssf创建workbook
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//3.使用sheet-----根据索引
XSSFSheet sheet = workbook.getSheetAt(0);
//日期格式
DataFormatter formatter = new DataFormatter();
for (Row cells : sheet) {
System.out.println(cells);
for (Cell cell : cells) {
/**
* 输出字符串数据,如果有其他类型,运行会报错,不会显示其他格式的数据
* 要输出其他格式,需选择输出的格式,如以下:
* getStringCellValue() 字符串数据
* getDateCellValue() 时间类型
*/
// System.out.println(cell.getStringCellValue());
//转换数据中含有日期的日期格式
String text = formatter.formatCellValue(cell);
System.out.println(text);
}
}
workbook.close();
}
效果图
写入文件数据
/**
* 写入数据
*/
@Test
public void write() throws IOException {
//创建Excel
XSSFWorkbook workbook = new XSSFWorkbook();
//2.创建sheet
XSSFSheet sheet = workbook.createSheet("sheet0");
//3.row cell-- 创建行表头
XSSFRow title = sheet.createRow(0);
//创建cell单元格--表头字段
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");
//写入流 -- 文件路径自己修改
FileOutputStream outputStream =
new FileOutputStream(new File("C:\\Users\\hp\\Desktop\\wwww.xlsx"));
workbook.write(outputStream);
outputStream.flush();
workbook.close();
}