springboot项目实现导出excel动态设置表头

Spring Boot实现Excel自定义导出

在这里插入图片描述

pom.xml

<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.9</version>
		</dependency>

ExcelCustomExportUtil.java

package com.jiuzhu.server.common.utils;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.poi.ss.usermodel.CellStyle.ALIGN_CENTER;
import static org.apache.poi.ss.usermodel.CellStyle.VERTICAL_CENTER;

public class ExcelCustomExportUtil {
    public static void exportExcel(HttpServletResponse response, List<String> headers, List<List<Object>> data) throws IOException {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("sheet1");
        Map<String, CellStyle> styles = createStyles(workbook);

        CellStyle style = sheet.getWorkbook().createCellStyle();
        // 设置字体为黑体
        Font font = sheet.getWorkbook().createFont();
        font.setFontName("黑体"); // 或者使用 "SimHei" 表示黑体
        font.setBoldweight((short) 1);      // 设置为粗体(黑体通常是粗体)
        style.setFont(font);
        style.setAlignment(ALIGN_CENTER);
        style.setVerticalAlignment(VERTICAL_CENTER);
        font.setColor(IndexedColors.WHITE.getIndex()); // 设置字体颜色为白色

        // 创建表头
        Row headerRow = sheet.createRow(0);
//        headerRow.setHeightInPoints(30);
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellStyle(styles.get("header"));
            cell.setCellValue(headers.get(i));
        }

        // 填充数据
        int rowIndex = 1;
        for (List<Object> rowData : data) {
            Row row = sheet.createRow(rowIndex++);
            for (int i = 0; i < rowData.size(); i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(rowData.get(i).toString());
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");

        // 将工作簿写入输出流
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }
        // 关闭工作簿
//        workbook.close();
//        workbook.cloneSheet(0);
    }
    /**
     * 创建表格样式
     *
     * @param wb 工作薄对象
     * @return 样式列表
     */
    private static Map<String, CellStyle> createStyles(Workbook wb) {
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();

        CellStyle style = wb.createCellStyle();
        style.setAlignment(ALIGN_CENTER);
        style.setVerticalAlignment(VERTICAL_CENTER);
        Font titleFont = wb.createFont();
        titleFont.setFontName("Arial");
        titleFont.setFontHeightInPoints((short) 16);
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);
        styles.put("title", style);

        style = wb.createCellStyle();
        style.setVerticalAlignment(VERTICAL_CENTER);
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(CellStyle.ALIGN_LEFT);
        styles.put("data1", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(ALIGN_CENTER);
        styles.put("data2", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(CellStyle.ALIGN_RIGHT);
        styles.put("data3", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
//		style.setWrapText(true);
        style.setAlignment(ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        return styles;
    }
}

使用

@RequestMapping("exportSearchList")
    public void exportSearchList(HttpServletResponse response) throws IOException {
        // 初始化表头和数据
        List<String> headers = Arrays.asList("列1", "列2", "列3");
        List<List<Object>> data = new ArrayList<>();
        data.add(Arrays.asList("数据1", "数据2", "数据3"));
        data.add(Arrays.asList("数据4", "数据5", "数据6"));

        ExcelCustomExportUtil.exportExcel(response, headers, data);
    }
### Spring Boot 动态选择字段导出 Excel 表格带自定义表头 为了实现Spring Boot项目中根据用户的选择动态导出带有特定表头Excel文件,可以采用如下方案: #### 准备工作 确保引入了必要的依赖库来处理Excel文件。对于此目的,`EasyPoi` 或 `EasyExcel` 是两个流行的选择。 #### 创建实体类 创建用于映射数据库记录或业务对象至Excel单元格的数据传输对象(DTO),并利用注解指定列名和其他属性配置。 ```java import cn.afterturn.easypoi.excel.annotation.Excel; public class ExportDTO { @Excel(name = "姓名", orderNum = "1") private String name; @Excel(name = "年龄", orderNum = "2") private Integer age; } ``` #### 构建服务层逻辑 编写服务于前端交互的服务接口,接收客户端传递过来的字段列表参数,并据此调整实际要导出的内容结构。 ```java @Service public class ExportService { public void export(List<String> selectedFields, HttpServletResponse response) throws IOException { List<ExportDTO> dataList = getData(); // 获取待导出数据 Workbook workbook = new SXSSFWorkbook(); Sheet sheet = workbook.createSheet("Data"); Row headerRow = sheet.createRow(0); Map<String, Field> fieldMap = getFieldMapping(ExportDTO.class); int colIndex = 0; for (String fieldName : selectedFields) { if (!fieldMap.containsKey(fieldName)) continue; // 跳过不存在的字段 Field field = fieldMap.get(fieldName); Excel excelAnnotation = field.getAnnotation(Excel.class); Cell cell = headerRow.createCell(colIndex++); cell.setCellValue(excelAnnotation.name()); } int rowIndex = 1; for (ExportDTO dataItem : dataList) { Row row = sheet.createRow(rowIndex++); colIndex = 0; for (String fieldName : selectedFields) { try { Object value = PropertyUtils.getProperty(dataItem, fieldName); Cell cell = row.createCell(colIndex++); if(value != null){ cell.setCellValue(String.valueOf(value)); } } catch (Exception e) { log.error(e.getMessage(), e); } } } ServletOutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); workbook.close(); outputStream.flush(); outputStream.close(); } private static Map<String, Field> getFieldMapping(Class<?> clazz) { Map<String, Field> map = new HashMap<>(); Arrays.stream(clazz.getDeclaredFields()) .filter(field -> field.isAnnotationPresent(Excel.class)) .forEach(field -> map.put(field.getName(), field)); return map; } } ``` 上述代码片段展示了如何通过反射机制读取给定类中的所有已标注`@Excel`注解的成员变量,并依据传入的字段集合构建对应的Excel头部信息以及填充具体数值[^3]。 #### 控制器部分 最后,在控制器中暴露HTTP API供外部调用,允许用户提交所需展示的字段名称数组作为查询条件之一。 ```java @RestController @RequestMapping("/api/export") public class ExportController { @Autowired private ExportService exportService; @GetMapping("/dynamic-fields") public void dynamicFieldExport(@RequestParam List<String> fields, HttpServletResponse response) throws Exception { response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=exported_data.xlsx"); this.exportService.export(fields, response); } } ``` 以上就是关于在Spring Boot应用程序内实现按需选取字段并生成相应格式化的Excel文档的大致流程说明[^1][^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值