SpringBoot 动态字段导出Excel多sheet文件

pom依赖

<!--hutool-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.22</version>
</dependency>

<!--autoPoi-->
<dependency>
    <groupId>org.jeecgframework</groupId>
    <artifactId>autopoi-web</artifactId>
    <version>1.4.6</version>
    <exclusions>
        <exclusion>
            <artifactId>xercesImpl</artifactId>
            <groupId>xerces</groupId>
        </exclusion>
    </exclusions>
</dependency>

<!--easyPoi-->
<!-- https://mvnrepository.com/artifact/cn.afterturn/easypoi-spring-boot-starter -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

工具类如下:

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.sql.Timestamp;

@Slf4j
public class ExcelUtils {
   
   

	/**
	 * 合并单元格
	 */
	public static void mergeRemarks(Workbook workbook, Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
   
   
		sheet.addMergedRegion(new CellRangeAddress(firstRow, // 第一行(0)
			lastRow, // last row(0-based)
			firstCol, // 第一列(基于0)
			lastCol // 最后一列(基于0)
		));
		//创建合并但未创建的单元格
		createCell(sheet, workbook.getCellStyleAt(24), firstRow, lastRow, firstCol, lastCol);
	}

	/**
	 * 根据行列遍历创建单元格
	 */
	public static void createCell(Sheet sheet, CellStyle cellStyle, int firstRow, int lastRow, int firstCol, int lastCol) {
   
   
		Row row;
		Cell cell;
		for (int i = firstRow; i <= lastRow; i++) {
   
   
			for(int j = firstCol; j <= lastCol; j++) {
   
   
				row = sheet.getRow(i);
				if(row == null) {
   
   
					row = sheet.createRow(i);
				}
				if(row.getCell(j) == null) {
   
   
					cell = row.createCell(j);
					cell.setCellStyle(cellStyle);
				}
			}
		}
	}

	public static CellStyle getCenterCellStyle(Workbook workbook){
   
   
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平布局:居中
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		cellStyle.setWrapText(true);
		cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
		cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
		cellStyle.setBorderTop(BorderStyle.THIN);//上边框
		cellStyle.setBorderRight(BorderStyle.THIN);//右边框
		return cellStyle;
	}


	/**
	 * excel文件流输出到浏览器
	 */
	public static void workBookWrite(String fileName, Workbook workbook, HttpServletResponse response) {
   
   
		try (OutputStream os = response.getOutputStream()) {
   
   
			response.
### Spring BootSheet 导出 Excel 文件 #### 创建 POJO 类 为了支持分 Sheet导出操作,首先需要定义一个用于存储每张工作表数据的 Java Bean。通常建议创建一个通用的基础类来保存公共字段,并让具体的业务实体继承该基础类。 ```java public class BaseExportEntity { private String id; private String sheetName; // Getters and Setters... } ``` 对于特定业务场景下的实体对象,则可以根据实际需求扩展此基类: ```java public class Employee extends BaseExportEntity { private String name; private int age; private double salary; // Constructors, getters and setters... } ``` #### 配置 EasyPoi 工具库 引入依赖项以便于后续处理 Excel 文档的操作,在 `pom.xml` 中添加如下配置[^1]: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>${easypoi.version}</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>${easypoi.version}</version> </dependency> ``` #### 编写控制器逻辑 编写 RESTful API 来响应前端发起的数据下载请求并执行相应的业务逻辑: ```java @RestController @RequestMapping("/api/export") public class ExportController { @Autowired private List<EmployeeService> employeeServices; @GetMapping(value="/employees", produces="application/vnd.ms-excel") public void exportEmployees(HttpServletResponse response){ Workbook workbook = new SXSSFWorkbook(); // 使用SXSSF可有效减少内存占用 try (workbook) { for(EmployeeService service : employeeServices){ Sheet sheet = workbook.createSheet(service.getDepartment()); // 设置标题行样式 Row headerRow = sheet.createRow(0); CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); font.setBold(true); style.setFont(font); // 添加列头信息 String[] headers = {"ID","姓名","年龄","工资"}; for(int i=0;i<headers.length;i++){ Cell cell = headerRow.createCell(i); cell.setCellValue(headers[i]); cell.setCellStyle(style); } // 填充员工记录到当前sheet中 List<Employee> employees = service.getAllEmployees(); int rowNum = 1; for(Employee emp : employees){ Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(emp.getId()); row.createCell(1).setCellValue(emp.getName()); row.createCell(2).setCellValue(emp.getAge()); row.createCell(3).setCellValue(emp.getSalary()); } } // 输出至客户端浏览器作为附件形式下载 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=exported_employees.xlsx"); ServletOutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); outputStream.flush(); } catch(IOException e){ throw new RuntimeException(e.getMessage(), e); } } } ``` 上述代码片段展示了如何通过循环遍历个部门的服务接口实例(`EmployeeService`),并将各个部门下所有的雇员列表分别填充到不同的工作表(Sheet)当中去。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值