java通用xls导出设计

博客 动态
0 143
羽尘
羽尘 2023-05-22 13:55:29
悬赏:0 积分 收藏

java通用xls导出设计

背景

在后端日常开发中总会有各种各样的导出需求,实现这个需求必须要解决的两个问题:

1、表头不能直接使用字段名,需要显示为中文,甚至还需要考虑国际化

2、值需要翻译,比如性别、状态之类的字段

现状

现在主流写的比较好的方法是定义一个对象,对象上用自定义的注解+easytrans

我的解决方案

定义要导入的字段

1、解决表头与字段的映射

2、表头加#进行后续split,解决翻译问题

{
    "parkls": {
        "parkname": "停车场",
        "carno": "车牌号",
        "intime": "进场时间",
        "outtime": "出场时间",
        "paytime": "支付时间",
        "parktime": "停车时长(单位:分钟)",
        "amt":"支付金额(单位:元)",
        "paytype":"支付方式#paytype",
        "paystatus":"支付状态#paystatus",
        "isrecharge":"是否重新计费#YN",
        "ismonthcard":"是否月卡抵扣#YN"        
    }
}
翻译
{
    "YN": {
        "Y": "",
        "N": ""
    },
    "paystatus": {
        "0": "待支付",
        "1": "已支付",
        "2": "已过期"
    },
    "paytype":{
        "0": "微信支付",
        "1": "月卡支付",
        "2": "现金",
        "3":"余额"
    }
}
加载配置
package com.xf.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.nio.charset.Charset;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.val;

public class ExcelDeal {

    public static JSONObject head;
    public static JSONObject trans;

    public synchronized static void load() throws FileNotFoundException {
        URL url = ClassLoader.getSystemResource("exporthead.json");
//        head = JSONUtil.readJSONObject(new File(url.getPath()), Charset.forName("utf-8"));
        String jsonstr = FileUtil.readString(new File(url.getPath()), Charset.forName("utf-8"));
        val config = JSONConfig.create().setOrder(true);
        head = JSONUtil.parseObj(jsonstr, config);
        url = ClassLoader.getSystemResource("trans.json");
//        trans = JSONUtil.readJSONObject(new File(url.getPath()), Charset.forName("utf-8"));
        jsonstr = FileUtil.readString(new File(url.getPath()), Charset.forName("utf-8"));
        trans = JSONUtil.parseObj(jsonstr, config);
    }
}
写xls

这个方法我就不上了,留点大家发挥的空间。

主要是分享下自已的思路,欢迎大家交流。

posted @ 2023-05-22 12:06  wujf  阅读(39)  评论(0编辑  收藏  举报
回帖
    羽尘

    羽尘 (王者 段位)

    2233 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员