easyExcel 导出自动添加序号

一、实体类添加字段
在这里插入图片描述
二、采用for循环元素的下标+1作为序号
在这里插入图片描述

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
在使用EasyExcel导出Excel时,你可以通过添加一个序号列来实现自增的编号。下面是一个示例,演示如何在导出Excel时添加自增序号列: ```java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller public class ExcelController { @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { // 创建数据列表 List<User> userList = new ArrayList<>(); userList.add(new User("张三", 20)); userList.add(new User("李四", 25)); userList.add(new User("王五", 30)); // 添加序号列 List<UserWithIndex> userListWithIndex = new ArrayList<>(); for (int i = 0; i < userList.size(); i++) { User user = userList.get(i); UserWithIndex userWithIndex = new UserWithIndex(i + 1, user.getName(), user.getAge()); userListWithIndex.add(userWithIndex); } // 设置响应头 response.setHeader("Content-Disposition", "attachment; filename=example.xlsx"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 创建Excel写入器 ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream(), UserWithIndex.class); // 创建工作表 ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet("Sheet1"); // 写入数据 sheetBuilder.doWrite(userListWithIndex); // 关闭写入器 writerBuilder.finish(); } // 定义用户实体类 public static class User { private String name; private int age; // 省略构造函数、getter和setter } // 带序号的用户实体类 public static class UserWithIndex { private int index; private String name; private int age; public UserWithIndex(int index, String name, int age) { this.index = index; this.name = name; this.age = age; } // 省略getter和setter } } ``` 在上述代码中,我们创建了一个新的 `UserWithIndex` 类,它包含了一个 `index` 属性来表示序号。在导出Excel之前,我们将原始数据列表转换为带序号的数据列表,并将其用于写入Excel。 确保在项目的依赖中包含了EasyExcel库的相关依赖项。运行该代码后,你将会得到一个带有自增序号列的Excel文件。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐睡睡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值