springboot整合easyPoi的注解方式导出excel文件

一、导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

二、创建注解导出类

/**
 * 商品  
 * Created on 2022/05/26.
 */  
@Data
@EqualsAndHashCode(callSuper = false)
public class Product {  

    @Excel(name = "商品SN", width = 20)  
    private String productSn;  
    @Excel(name = "商品名称", width = 20)  
    private String name;
    @Excel(name = "商品价格", width = 10)  
    private BigDecimal price;
    @Excel(name = "购买数量", width = 10, suffix = "件")  
    private Integer count;  
}
@Data
@EqualsAndHashCode(callSuper = false)
public class Order {  

    @Excel(name = "创建时间", width = 20, format = "yyyy/MM/dd",needMerge = true)
    private Date createTime;
    
    @Excel(name = "收货地址", width = 20,needMerge = true )
    private String receiverAddress;
	//表示一个集合,name为集合名称
    @ExcelCollection(name = "商品列表")
    private List<Product> productList;
	//表示一个集合,name为集合名称
    @ExcelCollection(name = "商品")
    private List<Product> productList1;
}

三、导出

1、简单导出

package com.shop.demo.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.shop.demo.util.Order;
import com.shop.demo.util.Product;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * EasyPoi导入导出测试Controller
 * Created  on 2022/5/25.
 */
@Controller
@RequestMapping("/easyPoi")
public class DemoController {

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void exportOrderList(ModelMap map,
                                HttpServletRequest request,
                                HttpServletResponse response) {
        List<Order> orderList = new ArrayList<>();
        Order order = new Order();
        order.setCreateTime(new Date());
        order.setReceiverAddress("广东省广州市天河区繁华街道科摩罗远盾杯二街22号305房");
        Product product = new Product();
        Product product1 = new Product();
        product.setName("This is the goods name");
        product.setCount(3);
        product.setPrice(new BigDecimal(445));
        product.setProductSn(UUID.randomUUID().toString());
        product1.setName("This is the goods name 1");
        product1.setCount(31);
        product1.setPrice(new BigDecimal(440));
        product1.setProductSn(UUID.randomUUID().toString()+"1");
        List<Product> list = new ArrayList<>();
        List<Product> list1 = new ArrayList<>();
        list.add(product);
        list1.add(product1);
        order.setProductList(list);
        order.setProductList1(list1);
        orderList.add(order);
        ExportParams params = new ExportParams();
        //ExportParams params = new ExportParams("", "订单列表", ExcelType.XSSF);
        //导出时排除一些字段
        params.setExclusions(new String[]{"ID", "出生日期", "性别"});
        map.put(NormalExcelConstants.DATA_LIST, orderList);
        map.put(NormalExcelConstants.CLASS, Order.class);
        map.put(NormalExcelConstants.PARAMS, params);
        map.put(NormalExcelConstants.FILE_NAME, "订单列表复杂表头");
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

}

在这里插入图片描述

2、自定义样式导出

2.1、创建自定义样式工具类

/**
 * EasyPoi导入导出工具类
 * Created  on 2022/5/26
 */
public class ExcelStyleUtil implements IExcelExportStyler {
    private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT");
    private static final short FONT_SIZE_TEN = 9;
    private static final short FONT_SIZE_ELEVEN = 10;
    private static final short FONT_SIZE_TWELVE = 10;
    /**
     * 大标题样式
     */
    private CellStyle headerStyle;
    /**
     * 每列标题样式
     */
    private CellStyle titleStyle;
    /**
     * 数据行样式
     */
    private CellStyle styles;

    public ExcelStyleUtil(Workbook workbook) {
        this.init(workbook);
    }

    /**
     * 初始化样式
     *
     * @param workbook
     */
    private void init(Workbook workbook) {
        this.headerStyle = initHeaderStyle(workbook);
        this.titleStyle = initTitleStyle(workbook);
        this.styles = initStyles(workbook);
    }

    /**
     * 大标题样式
     *
     * @param color
     * @return
     */
    @Override
    public CellStyle getHeaderStyle(short color) {
        return headerStyle;
    }

    /**
     * 每列标题样式
     *
     * @param color
     * @return
     */
    @Override
    public CellStyle getTitleStyle(short color) {
        return titleStyle;
    }

    /**
     * 数据行样式
     *
     * @param parity 可以用来表示奇偶行
     * @param entity 数据内容
     * @return 样式
     */
    @Override
    public CellStyle getStyles(boolean parity, ExcelExportEntity entity) {
        return styles;
    }

    /**
     * 获取样式方法
     *
     * @param dataRow 数据行
     * @param obj     对象
     * @param data    数据
     */
    @Override
    public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) {
        return getStyles(true, entity);
    }

    /**
     * 模板使用的样式设置
     */
    @Override
    public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) {
        return null;
    }

    /**
     * 初始化--大标题样式
     *
     * @param workbook
     * @return
     */
    private CellStyle initHeaderStyle(Workbook workbook) {
        CellStyle style = getBaseCellStyle(workbook);
        //style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true));
        return style;
    }

    /**
     * 初始化--每列标题样式
     *
     * @param workbook
     * @return
     */
    private CellStyle initTitleStyle(Workbook workbook) {
        CellStyle style = getBaseCellStyle(workbook);
        //style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false));
        //背景色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return style;
    }

    /**
     * 初始化--数据行样式
     *
     * @param workbook
     * @return
     */
    private CellStyle initStyles(Workbook workbook) {
        CellStyle style = getBaseCellStyle(workbook);
        //style.setFont(getFont(workbook, FONT_SIZE_TEN, false));
        style.setDataFormat(STRING_FORMAT);
        return style;
    }

    /**
     * 基础样式
     *
     * @return
     */
    private CellStyle getBaseCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        //下边框
        style.setBorderBottom(BorderStyle.THIN);
        //左边框
        style.setBorderLeft(BorderStyle.THIN);
        //上边框
        style.setBorderTop(BorderStyle.THIN);
        //右边框
        style.setBorderRight(BorderStyle.THIN);
        //水平居中
        style.setAlignment(HorizontalAlignment.CENTER);
        //上下居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置自动换行
        style.setWrapText(true);
        return style;
    }

    /**
     * 字体样式
     *
     * @param size   字体大小
     * @param isBold 是否加粗
     * @return
     */
    private Font getFont(Workbook workbook, short size, boolean isBold) {
        Font font = workbook.createFont();
        //字体样式
        font.setFontName("宋体");
        //是否加粗
        font.setBold(isBold);
        //字体大小
        font.setFontHeightInPoints(size);
        return font;
    }
}

2.2、导出

package com.shop.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.shop.demo.util.ExcelExportStyler;
import com.shop.demo.util.ExcelStyleUtil;
import com.shop.demo.util.Order;
import com.shop.demo.util.Product;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * EasyPoi导入导出测试Controller
 * Created  on 2022/5/26
 */
@Controller
@RequestMapping("/easyPoi")
public class DemoController01 {

    @RequestMapping(value = "/export1", method = RequestMethod.GET)
    public void exportOrderList( HttpServletResponse response) throws IOException {
        List<Order> orderList = new ArrayList<>();
        Order order = new Order();
        setData(order,orderList);
        ExportParams params = new ExportParams();
        //ExportParams params = new ExportParams("", "订单列表", ExcelType.XSSF);
        //导出时排除一些字段
        params.setExclusions(new String[]{"ID", "出生日期", "性别"});
        params.setStyle(ExcelStyleUtil.class);
        Workbook workbook =  ExcelExportUtil.exportExcel(params, Order.class, orderList);

        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单列表复杂表头" + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    public void  setData(Order order,List<Order> orderList){
        for (int i=0; i< 10;i++){
            order.setCreateTime(new Date());
            order.setReceiverAddress("广东省广州市天河区繁华街道科摩罗远盾杯二街22号305房");
            Product product = new Product();
            Product product1 = new Product();
            product.setName("This is the goods name");
            product.setCount(3 + i);
            product.setPrice(new BigDecimal(445 + i));
            product.setProductSn(UUID.randomUUID().toString());
            product1.setName("This is the goods name 1");
            product1.setCount(31 + i);
            product1.setPrice(new BigDecimal(440 + i ));
            product1.setProductSn(UUID.randomUUID().toString()+"1");
            List<Product> list = new ArrayList<>();
            List<Product> list1 = new ArrayList<>();
            list.add(product);
            list1.add(product1);
            order.setProductList(list);
            order.setProductList1(list1);
            orderList.add(order);
        }

    }
}

在这里插入图片描述

3、自定义标题样式导出

package com.shop.demo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.shop.demo.util.ExcelStyleUtil;
import com.shop.demo.util.Order;
import com.shop.demo.util.Product;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * EasyPoi导入导出测试Controller
 * Created  on 2022/5/26
 */
@Controller
@RequestMapping("/easyPoi")
public class DemoController02 {

    @RequestMapping(value = "/export2", method = RequestMethod.GET)
    public void exportOrderList( HttpServletResponse response) throws IOException {
        List<Order> orderList = new ArrayList<>();
        Order order = new Order();
        setData(order,orderList);
        ExportParams params = new ExportParams();
        //ExportParams params = new ExportParams("", "订单列表", ExcelType.XSSF);
        //导出时排除一些字段
        params.setExclusions(new String[]{"ID", "出生日期", "性别"});
        params.setStyle(ExcelStyleUtil.class);
        Workbook workbook =  ExcelExportUtil.exportExcel(params, Order.class, orderList);
        //单元格样式设置
        //表头第1~2格
        setCellStyle(0,0, 2,IndexedColors.GREY_25_PERCENT.getIndex(),workbook);
        //表头第3格第一行
        setCellStyle(0,2, 1, IndexedColors.LIME.getIndex(),workbook);
        //表头第3格第二行
        setCellStyle(1,2, 4,IndexedColors.LIME.getIndex(),workbook);
        //表头第7格第一行
        setCellStyle(0,6, 1,IndexedColors.TAN.getIndex(),workbook);
        //表头第7格第二行
        setCellStyle(1,6, 4,IndexedColors.TAN.getIndex(),workbook);

        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单列表复杂表头" + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    public void setCellStyle(int rowNumber,int cellNumber,int size, short indexedColor,Workbook workbook){
        //设置单元格颜色
        CellStyle style = workbook.createCellStyle();
        Sheet sheet = workbook.getSheetAt(0);
        //设置单元格颜色(颜色对应枚举会放在下面)
        style.setFillForegroundColor(indexedColor);
        //全部填充 (填充枚举对应的样式也会放在下面)
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //设置水平方向字体居中
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直方向字体居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN); //下边框
        style.setBorderLeft(BorderStyle.THIN);//左边框
        style.setBorderTop(BorderStyle.THIN);//上边框
        style.setBorderRight(BorderStyle.THIN);//右边框
        //合并单元格样式设置
        CellRangeAddress mergedRegion = sheet.getMergedRegion(2);
        RegionUtil.setBorderRight(BorderStyle.THIN, mergedRegion, sheet); // 右边框
        RegionUtil.setBorderTop(BorderStyle.THIN, mergedRegion, sheet); // 上边框
        CellRangeAddress mergedRegion2 = sheet.getMergedRegion(3);
        RegionUtil.setBorderRight(BorderStyle.THIN, mergedRegion2, sheet); // 右边框
        RegionUtil.setBorderTop(BorderStyle.THIN, mergedRegion2, sheet); // 上边框
        for (int i = 0; i < size; i++) {
            Row row = sheet.getRow(rowNumber );
            Cell cell = row.getCell(cellNumber + i);

            cell.setCellStyle(style);
        }

    }

    public void  setData(Order order,List<Order> orderList){
        for (int i=0; i< 10;i++){
            order.setCreateTime(new Date());
            order.setReceiverAddress("广东省广州市天河区繁华街道科摩罗远盾杯二街22号305房");
            Product product = new Product();
            Product product1 = new Product();
            product.setName("This is the goods name");
            product.setCount(3 + i);
            product.setPrice(new BigDecimal(445 + i));
            product.setProductSn(UUID.randomUUID().toString());
            product1.setName("This is the goods name 1");
            product1.setCount(31 + i);
            product1.setPrice(new BigDecimal(440 + i ));
            product1.setProductSn(UUID.randomUUID().toString()+"1");
            List<Product> list = new ArrayList<>();
            List<Product> list1 = new ArrayList<>();
            list.add(product);
            list1.add(product1);
            order.setProductList(list);
            order.setProductList1(list1);
            orderList.add(order);
        }

    }
}

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于你的问题,我会为你详细介绍SpringBootEasyPoi如何实现数据导出。下面是实现步骤及代码示例: 步骤1:在pom.xml中添加EasyPoi依赖 ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.2.0</version> </dependency> ``` 步骤2:定义导出的实体类,并使用注解配置导出的列名和顺序 ```java public class User{ @Excel(name = "用户名", orderNum = "1") private String username; @Excel(name = "密码", orderNum = "2") private String password; // ...其他属性及getter/setter方法 } ``` 步骤3:编写导出Excel数据的控制器 ```java @RestController @RequestMapping("/api/user") public class UserController { @Autowired private UserService userService; @GetMapping("/export") public void exportData(@RequestParam(name = "fields") String fields, HttpServletResponse response) { // 处理表头列名 String[] titles = fields.split(","); // 查询数据库中所有用户信息 List<User> userList = userService.findAll(); // 根据用户选择的字段过滤掉不需要导出的列 for (int i = 0; i < titles.length; i++) { boolean isMatch = false; for (Field field : User.class.getDeclaredFields()) { if (field.isAnnotationPresent(Excel.class)) { Excel annotation = field.getAnnotation(Excel.class); if (annotation.name().equals(titles[i])) { isMatch = true; break; } } } if (!isMatch) { titles[i] = null; } } // 利用EasyPoi导出Excel ExportParams exportParams = new ExportParams("", "用户信息"); exportParams.setCreateHeadRows(true); exportParams.setHeadRows(1); Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, userList, null, titles, null); try (OutputStream outputStream = response.getOutputStream()) { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("用户信息.xlsx")); workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上就是导出Excel的完整代码,其中针对用户选择需要导出的字段进行校验的部分,使用了反射机制获取注解信息进行匹配。为保证Excel格式的一致性,我们还使用了EasyPoi提供的ExportParams配置Excel表头等属性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值