SpringBoot集成CSV的导出

1、pom依赖

 <!-- csv的导出工具类-->
        <dependency>
            <groupId>net.sf.supercsv</groupId>
            <artifactId>super-csv</artifactId>
            <version>2.4.0</version>
        </dependency>

2、工具类

ReportCsvUtils.java

package com.zhz.util;

import org.apache.commons.lang3.StringUtils;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * 导出工具类
 **/
public class ReportCsvUtils {

    public static void reportList(
            HttpServletResponse response,
            String[] header,
            String[] properties,
            String fileName,
            List<?> soureList
    ) throws Exception {

        if (header == null || properties == null || soureList == null || header.length <= 0 || properties.length <= 0 || soureList.size() <= 0)
            return;
        if (StringUtils.isBlank(fileName)) {
            fileName = "1.csv";
        }
        response.setContentType("application/csv");
        response.setCharacterEncoding("GBK");
        response.setHeader("Content-FileName", URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);
        csvWriter.writeHeader(header);
        for (Object obj : soureList) {
            csvWriter.write(obj, properties);
        }
        csvWriter.close();


    }


    public static void reportListCsv(
            HttpServletResponse response,
            String[] header,
            String[] properties,
            String fileName,
            List<?> soureList,
            CellProcessor[] PROCESSORS
    ) throws Exception {

        if (header == null || properties == null || soureList == null || header.length <= 0 || properties.length <= 0 || soureList.size() <= 0)
            return;
        if (StringUtils.isBlank(fileName)) {
            fileName = "1.csv";
        }
        response.setContentType("application/csv");
        response.setCharacterEncoding("GBK");
        response.setHeader("Content-FileName", URLEncoder.encode(fileName, "UTF-8"));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");


        ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(), CsvPreference.STANDARD_PREFERENCE);
        csvWriter.writeHeader(header);
        for (Object obj : soureList) {
            csvWriter.write(obj, properties, PROCESSORS);
        }
        csvWriter.close();
    }


}

3、数据

注意:里面的数据,可以放properties或者yml中

package com.zhz.constants;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author :zhz
 * @date :Created in 2021/05/12
 * @version: V1.0
 * @slogan: 天下风云出我辈,一入代码岁月催
 * @description:
 **/
public class PaymentConstant {
    private final static Map<String, String> payment=new ConcurrentHashMap<>();

    public PaymentConstant() {
        payment.put("alipay","支付宝");
        payment.put("cai1pay","财易付");
        payment.put("bank","银联");
        payment.put("linepay","在线支付");
    }

    public static String getTypeName(String type){
        if (payment.containsKey(type)){
            return payment.get(type);
        }else {
            return "未知";
        }
    }
}
package com.zhz.constants;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author :zhz
 * @date :Created in 2021/05/12
 * @version: V1.0
 * @slogan: 天下风云出我辈,一入代码岁月催
 * @description:
 **/
public class VerifyConstant {
    private final static Map<Integer, String> verify=new ConcurrentHashMap<>();

    public VerifyConstant() {
        verify.put(0,"待审核");
        verify.put(1,"审核通过");
        verify.put(2,"拒绝");
        verify.put(3,"充值成功");
    }
    public static String getStatus(int num){
        if (verify.containsKey(num)){
            return verify.get(num);
        }else {
            return "未知";
        }
    }
}

3、controller层

  @GetMapping("/records/export")
    @ApiOperation("充值记录导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coinId", value = "当前页"),
            @ApiImplicitParam(name = "userId", value = "用户的ID"),
            @ApiImplicitParam(name = "userName", value = "用户的名称"),
            @ApiImplicitParam(name = "mobile", value = "用户的手机号"),
            @ApiImplicitParam(name = "status", value = "充值的状态"),
            @ApiImplicitParam(name = "numMin", value = "充值金额的最小值"),
            @ApiImplicitParam(name = "numMax", value = "充值金额的最小值"),
            @ApiImplicitParam(name = "startTime", value = "充值开始时间"),
            @ApiImplicitParam(name = "endTime", value = "充值结束时间"),
    })
    public void recordsExport(Long coinId,
                              Long userId,
                              String userName,
                              String mobile,
                              Byte status,
                              String numMin,
                              String numMax,
                              String startTime,
                              String endTime) {
        //创建分页对象,指定当前页的显示的条数
        Page<CashRecharge> page = new Page<>(1, 10000);
        //分页条件查询充值记录
        Page<CashRecharge> rechargePages = cashRechargeService.findByPage(page, coinId, userId, userName, mobile, status, numMin, numMax, startTime, endTime);
        //获取数据列表
        List<CashRecharge> records = rechargePages.getRecords();
        //如果获取的数据不为空
        if (!CollectionUtils.isEmpty(records)) {
            //表头
            String[] header = {"ID", "用户ID", "用户名", "真实用户名", "充值币种", "充值金额(USDT)", "手续费", "到账金额(CNY)", "充值方式", "充值订单", "参考号", "充值时间", "完成时间", "状态", "审核备注", "审核级数"};
            //表头对应的属性(也就是我们实体的字段,一一对应)
            String[] properties = {"id", "userId", "username", "realName", "coinName", "num", "fee", "mum", "type", "tradeno", "remark", "created", "lastTime", "statusStr", "auditRemark", "step"};
            //创建适配器
            CellProcessorAdaptor longToStringAdapter = new CellProcessorAdaptor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    return (T) String.valueOf(o);
                }
            };
            // 对于金额,需要8位有效数字,金额
            DecimalFormat decimalFormat = new DecimalFormat("0.00000000");
            CellProcessorAdaptor moneyCellProcessorAdaptor = new CellProcessorAdaptor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    BigDecimal num = (BigDecimal) o;
                    return (T) (decimalFormat.format(num));
                }
            };
            //      @ApiModelProperty(value = "类型:alipay,支付宝;cai1pay,财易付;bank,银联;")
            CellProcessorAdaptor typeAdapter = new CellProcessorAdaptor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    String type = String.valueOf(o);
                    return (T) PaymentConstant.getTypeName(type);
                }
            };
            //日期适配
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            CellProcessorAdaptor timeCellProcessorAdaptor = new CellProcessorAdaptor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    if (o == null) {
                        return (T) "";
                    }
                    Date date = (Date) o;
                    String dateStr = simpleDateFormat.format(date);
                    return (T) dateStr;
                }
            };
            // 0-待审核;1-审核通过;2-拒绝;3-充值成功
            CellProcessorAdaptor statusCellProcessorAdaptor = new CellProcessorAdaptor() {

                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    Integer status = Integer.valueOf(String.valueOf(o));
                    return (T) VerifyConstant.getStatus(status);
                }
            };
            //进行类型适配
            CellProcessor[] PROCESSOR = new CellProcessor[]{
                    longToStringAdapter, longToStringAdapter, null, null, null, // "ID", "用户ID", "用户名", "真实用户名", "充值币种",
                    moneyCellProcessorAdaptor, moneyCellProcessorAdaptor, moneyCellProcessorAdaptor, typeAdapter,  // "充值金额(USDT)", "手续费", "到账金额(CNY)", 充值方式"
                    null, null, timeCellProcessorAdaptor, timeCellProcessorAdaptor,//充值订单", "参考号", "充值时间", "完成时间
                    statusCellProcessorAdaptor, null, null //状态 "审核备注", "审核级数"
            };
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            try {
                ReportCsvUtils.reportListCsv(requestAttributes.getResponse(),header,properties,"场外交易充值审核.csv",records,PROCESSOR);
            } catch (Exception e) {
                log.error("导出文件失败,原因:" + e.getMessage());
            }
        }
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

zhz小白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值