1、导入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.3</version>
</dependency>
<!-- excel导出依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2、代码
Apache POI既可以将数据写入Excel文件,也可以读取Excel文件中的数据,
2.1 基于POI写入excel文件
public static void write() throws IOException {
// 在内存重创建一个excel对象
XSSFWorkbook excel = new XSSFWorkbook();
// 创建sheet页
XSSFSheet sheet = excel.createSheet("itcast");
// 在sheet页中创建行,0表示第1行
XSSFRow row1 = sheet.createRow(0);
// 创建单元格,row1.createCell()
// 设置单元格值 setCellValue("姓名")
row1.createCell(1).setCellValue("姓名");
row1.createCell(2).setCellValue("城市");
// 输出工作簿到文件或输出流
FileOutputStream out = new FileOutputStream(new File("D:\\itcast.xlsx"));
//通过输出流将内存中的Excel文件写入到磁盘上
excel.write(out);
out.flush();
out.close();
excel.close();
}
2.2 读取excel文件
public static void read() throws IOException {
FileInputStream input = new FileInputStream(new File("D:\\itcast.xlsx"));
XSSFWorkbook excel = new XSSFWorkbook(input);
XSSFSheet sheet = excel.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i=0;i<=lastRowNum;i++){
XSSFRow row = sheet.getRow(i); // 获取行
XSSFCell cell1 = row.getCell(1); // 获取行的第2个单元格
String cellValue1 = cell1.getStringCellValue();//获取单元格的文本内容
XSSFCell cell2 = row.getCell(2);
String cellValue2 = cell2.getStringCellValue();
System.out.println(cellValue1+" "+cellValue2);
input.close();
excel.close();
}