操作Excel

EasyExcel 导入导出

是阿里巴巴开源的一个 Excel 处理工具,专门用于简化 Excel 文件的读写操作。

1、 添加 Maven 依赖

<dependency>  
    <groupId>com.alibaba</groupId>  
    <artifactId>easyexcel</artifactId>  
    <version>3.2.0</version> <!-- 使用最新版本 -->  
</dependency>  

2、定义数据模型

首先需要定义一个数据模型类,用于映射 Excel 中的每一行数据。

import com.alibaba.excel.annotation.ExcelProperty;  
import com.alibaba.excel.annotation.WorkbookStyle;  
import lombok.Data;  

@Data  
public class UserData {  
    
    @ExcelProperty("用户ID")  
    private Long id;  

    @ExcelProperty("用户名")  
    private String name;  

    @ExcelProperty("年龄")  
    private Integer age;  
} 

3. 写入 Excel 文件

public static void main(String[] args) {  
   String fileName = "user_data.xlsx";  
   List<UserData> data = new ArrayList<>();  
   data.add(new UserData(1L, "张三", 25));  
   data.add(new UserData(2L, "李四", 30));  
   // 写入 Excel  
   EasyExcel.write(fileName, UserData.class)  
              .sheet("用户信息") // 工作表名称  
     .doWrite(data);  
}  

4. 读取 Excel 文件

public static void main(String[] args) {  
	  String fileName = "user_data.xlsx";  
	  // 读取 Excel  
      EasyExcel.read(fileName, UserData.class, new AnalysisEventListener<UserData>() {  
      @Override  
      public void invoke(UserData userData, AnalysisContext analysisContext) {  
         System.out.println("读取到数据: " + userData);  
      }  

       @Override  
       public void doAfterAllAnalysed(AnalysisContext analysisContext) {  
                // 读取完所有数据后的操作  
              System.out.println("所有数据读取完毕!");  
      }  
   }).sheet().doRead();  
}  

注解:你可以使用不同的注解来配置字段映射、格式化等,例如 @ExcelProperty 用于定义 Excel 列名,@DateTimeFormat 用于日期格式化等。

根据Excel模板写入导出

引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>5.2.5</version>
</dependency>

写入Excel文件

//在内存中创建一个Excel文件
XSSFWorkbook excel = new XSSFWorkbook();
//在Excel文件中创建一个Sheet页
XSSFSheet sheet = excel.createSheet("info");
//在Sheet中创建行对象,rownum编号从0开始

XSSFRow row = sheet.createRow(1);
//创建单元格并且写入文件内容
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("城市");
//创建一个新行
row = sheet.createRow(2);
row.createCell(1).setCellValue("张三");
row.createCell(2).setCellValue("北京");
row = sheet.createRow(3);
row.createCell(1).setCellValue("李四");
row.createCell(2).setCellValue("南京");
//通过输出流将内存中的Excel文件写入到磁盘
FileOutputStream out = new FileOutputStream(new File("D:\\info.xlsx"));
excel.write(out);
//关闭资源
out.close();
excel.close();

读取Excel文件

InputStream in = new FileInputStream(new File("D:\\info.xlsx"));
//读取磁盘上已经存在的Excel文件
XSSFWorkbook excel = new XSSFWorkbook(in);
//读取Excel文件中的第一个Sheet页
XSSFSheet sheet = excel.getSheetAt(0);
//获取Sheet中最后一行的行号
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum ; i++) {
  //获得某一行
  XSSFRow row = sheet.getRow(i);
  //获得单元格对象
  String cellValue1 = row.getCell(1).getStringCellValue();
  String cellValue2 = row.getCell(2).getStringCellValue();
  System.out.println(cellValue1 + " " + cellValue2);
}
//关闭资源
in.close();
excel.close();

先读取Excel模板,再写入数据

InputStream in = new FileInputStream(new File("D:\\info.xlsx"));
//读取磁盘上已经存在的Excel文件
XSSFWorkbook excel = new XSSFWorkbook(in);
//读取Excel文件中的第一个Sheet页
XSSFSheet sheet = excel.getSheetAt(0);
//获取Sheet中最后一行的行号
int lastRowNum = sheet.getLastRowNum();
// 设置表格样式
CellStyle style = excel.createCellStyle();
 // 设置上边框
style.setBorderTop(BorderStyle.THIN);
// 设置下边框
style.setBorderBottom(BorderStyle.THIN);
// 设置左边框
style.setBorderLeft(BorderStyle.THIN);
// 设置右边框
style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
//在Sheet中创建行对象,rownum编号从lastRowNum开始
XSSFRow row = sheet.createRow(lastRowNum++);
//创建单元格并且写入文件内容
row.createCell(1).setCellValue("姓名");
row.createCell(2).setCellValue("城市");
//创建一个新行
row = sheet.createRow(lastRowNum+2);
row.createCell(1).setCellValue("张三"); 
row.createCell(2).setCellValue("北京");

//通过输出流将内存中的Excel文件写入到磁盘
FileOutputStream out = new FileOutputStream(new File("D:\\info.xlsx"));
excel.write(out);
//关闭资源
out.close();
excel.close();
posted @   CH_song  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示