工具类-把对象转为字符串导出为json文件

本文介绍了一种将数据对象转换为字符串,并将其导出为JSON文件的方法,适用于前端传值场景,便于数据导入和备份。

把对象转为字符串导出为json文件

根据前段传值获取数据对象,转成String,然后就可以在浏览器上面导出json或者TXT文件,备导入数据使用。

public class OpExportFileUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(OpExportFileUtil.class);

    private HttpServletResponse response;
    private HttpServletRequest request;

    // 文件名
    private String fileName = "export";
    //文件保存路径
    private String fileDir;
    //sheet名
    private String sheetName = "sheet1";
    //备注内容
    private String titleRemark;
    //必填项设置列表
    private List<Integer> mandatoryTitle;
    //表头字体
    private String titleFontType = "Arial Unicode MS";
    //表头字号
    private short titleFontSize = 12;
    //正文字体
    private String contentFontType = "Arial Unicode MS";
    //正文字号
    private short contentFontSize = 12;
    //首行备注字体
    private String titleRemarkFontType = "宋体";
    //首行备注字号
    private short titleRemarkFontSize = 18;
    //首行备注高度
    private short titleRemarkCellHeight = 18;
    //首行备注宽度(列号,从0起)
    private short titleRemarkEndColNum = 12;
    //是否需要序号列
    private boolean needSequenceColumn = true;
    //是否需要首行备注
    private boolean needTitleRemark = false;
    //是否需要标注必填项
    private boolean needMandatoryTitle = false;
    //说明的背景颜色
    private Short titleRemarkBackGroundColorIndex = null;
    //标题的北京颜色
    private Short headerBackGroundColorIndex = null;

    private XSSFWorkbook workbook = null;

    // 导出的格式均为文本 added by wentian 2018/4/9
    private boolean isCellStylePureString = false;

    //模板中是否需要下拉框,只适用于数量较小的情况
    private boolean isNeedDropDownBox = false;
    private int maxDropDownRowShowSize = 50000;  //能展示下拉框的最大行数
    private List<String[]> dropDownDatas;  //下拉框的数据
    private int[] dropDownColNums; //下拉框对应的列下标
    private boolean titleRemarkBold = true;

    public OpExportFileUtil setIsCellStylePureString(boolean flag) {
        this.isCellStylePureString = flag;
        return this;
    }


    public OpExportFileUtil(String fileDir, String sheetName) {
        this.fileDir = fileDir;
        this.sheetName = sheetName;
        workbook = new XSSFWorkbook();
    }

    public OpExportFileUtil(HttpServletResponse response, String fileName) {
        this.response = response;
        this.fileName = fileName;
    }

    /**
     * 设置表头字体.
     *
     * @param titleFontType
     */
    public OpExportFileUtil setTitleFontType(String titleFontType) {
        this.titleFontType = titleFontType;
        return this;
    }

    public OpExportFileUtil setTitleRemarkColorIndex(Short index) {
        this.titleRemarkBackGroundColorIndex = index;
        return this;
    }

    public OpExportFileUtil setHeaderColorIndex(Short index) {
        this.headerBackGroundColorIndex = index;
        return this;
    }

    public OpExportFileUtil setNeedSequenceColumn(boolean needSequenceColumn) {
        this.needSequenceColumn = needSequenceColumn;
        return this;
    }

    public OpExportFileUtil setNeedTitleRemark(boolean needTitleRemark) {
        this.needTitleRemark = needTitleRemark;
        return this;
    }

    public OpExportFileUtil setNeedMandatoryTitle(boolean needMandatoryTitle) {
        this.needMandatoryTitle = needMandatoryTitle;
        return this;
    }

    public OpExportFileUtil setTitleRemarkBold(boolean titleRemarkBold) {
        this.titleRemarkBold = titleRemarkBold;
        return this;
    }


    /**
     * 设置表头字体大小.
     *
     * @param titleFontSize
     */
    public OpExportFileUtil setTitleFontSize(short titleFontSize) {
        this.titleFontSize = titleFontSize;
        return this;
    }

    /**
     * 设置正文字体.
     *
     * @param contentFontType
     */
    public OpExportFileUtil setContentFontType(String contentFontType) {
        this.contentFontType = contentFontType;
        return this;
    }

    /**
     * 设置正文字号.
     *
     * @param contentFontSize
     */
    public OpExportFileUtil setContentFontSize(short contentFontSize) {
        this.contentFontSize = contentFontSize;
        return this;
    }

    /**
     * 设置首行备注信息
     *
     */
    public OpExportFileUtil setTitleRemark(String titleRemark, short titleRemarkFontSize, short titleRemarkCellHeight) {
        this.titleRemark = titleRemark;
        this.titleRemarkFontSize = titleRemarkFontSize;
        this.titleRemarkCellHeight = titleRemarkCellHeight;
        return this;
    }


    /**
     * 设置首行备注信息
     *
     */
    public OpExportFileUtil setTitleRemark(String titleRemark, short titleRemarkFontSize, short titleRemarkCellHeight, short remarkEndColNum) {
        this.titleRemark = titleRemark;
        this.titleRemarkFontSize = titleRemarkFontSize;
        this.titleRemarkCellHeight = titleRemarkCellHeight;
        this.titleRemarkEndColNum = remarkEndColNum;
        return this;
    }


    public OpExportFileUtil setMandatoryTitle(List<Integer> mandatoryTitle) {
        this.mandatoryTitle = mandatoryTitle;
        return this;
    }


    public OpExportFileUtil setDropDownBoxData(List<String[]> dropDownDatas, int[] dropDownColNums) {
        this.dropDownDatas = dropDownDatas;
        this.dropDownColNums = dropDownColNums;
        if (null != dropDownDatas && dropDownDatas.size() > 0 && null != dropDownColNums
                && dropDownColNums.length > 0) {
            this.isNeedDropDownBox = true;
        }
        return this;
    }

    /**
     * 数据导出为json文件
     * @param exportContentStr
     */
    public void writeOpExportFileJson(String exportContentStr) {
        try (OutputStream out = getOutputStream();) {
            // ByteArrayOutputStream excelStream = buildExcel(propertyNames, titleName, false, columnSizes, dataList);
            out.write(exportContentStr.getBytes());
            out.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private OutputStream getOutputStream() throws IOException {
        if (fileDir != null) {
            // 保存文件
            return new FileOutputStream(fileDir);
        } else {
            // 从response中获取输出流
            buildResponse();
            return response.getOutputStream();
        }
    }

    private void buildResponse() throws UnsupportedEncodingException {
        // 设置文件返回类型
        fileName = fileName + ".json";
        response.setContentType("application/msexcel");

        // 默认处理
        response.setHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));

        if (null == request) {
            return;
        }

        String Agent = request.getHeader("User-Agent");
        if (null != Agent && (Agent.toLowerCase().indexOf("firefox") != -1)) {
            //对火狐做特殊处理
            response.setHeader("Content-Disposition",
                    String.format("attachment;filename*=utf-8'zh_cn'%s", URLEncoder.encode(fileName, "utf-8")));
        }
    }

    public void writeTXT(String path, String title, String content, HttpServletResponse response) {
        try {
            // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
            /* 写入Txt文件 */
            File writename = new File(path);// 相对路径,如果没有则要建立一个新的output。txt文件
            if (!writename.exists()) {
                writename.mkdirs();
            }
            writename = new File(path + "\\" + title);// 相对路径,如果没有则要建立一个新的output。txt文件
            writename.createNewFile(); // 创建新文件
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(content); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

每天努力一点,每天都在进步。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

powerfuler

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

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

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

打赏作者

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

抵扣说明:

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

余额充值