记录导出xml和csv数据

本文档记录了如何借助Hutool工具包进行XML和CSV数据的导出,包括相关依赖引入和实际业务功能的实现过程。
摘要由CSDN通过智能技术生成

依赖hutool工具包

public static void main(String[] args) {
        GeneralXML generalXML = new GeneralXML();
        String resource = GeneralXML.class.getResource("/opcTemplate.xml").getPath();
        String parent = new File(resource).getParent() + "/opcConfig";
        System.out.println(resource);
        System.out.println(System.lineSeparator());
        String s = GeneralXML.readFileByer(resource);
        MessageFormat mf = new MessageFormat(s);
        StringBuffer sb = new StringBuffer();
        sb.append(generalXML.head);
        sb.append(generalXML.root_start);
        sb.append(mf.format(new Object[]{" ", " ", " ", " ", " ", " ", " ", "/opcConfig/testXml.xml"}));
        sb.append(generalXML.root_end);
        System.out.println(sb.toString());
        String path = "/Users/lihongxing/Downloads/";
        File file = new File(parent);
        if (file.exists()) {
            file.mkdirs();
        }
        //指定路径和编码
        Document document = XmlUtil.parseXml(sb.toString());
        XmlUtil.toFile(document, parent + "/testXml.xml");
        CsvWriter writer = CsvUtil.getWriter(parent + "/testWrite.csv", CharsetUtil.CHARSET_UTF_8);
        Field[] declaredFields = PointInfoExportCSV.class.getDeclaredFields();
        List<String> collect = Arrays.stream(declaredFields).sequential().map(fi -> fi.getName()).collect(Collectors.toList());
        String[] strings = collect.toArray(new String[collect.size()]);
        List<Object> list = new ArrayList<>();
        list.add(strings);
        list.add(new String[]{"a2", "b2", "c2"});
        list.add(new String[]{"a3", "b3", "c4"});
        writer.write(
                list
        );

    }
public class GeneralXML {
    public final String head = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
    public final String root_start = "<config>\n";
    public final String root_end = "\n</config>";

    public static String readFileByer(String filePath) {
        StringBuffer sb = new StringBuffer();
        File file = new File(filePath);
        FileReader fr = null;

        try {
            fr = new FileReader(file);
        } catch (FileNotFoundException var16) {
            var16.printStackTrace();
        }

        BufferedReader br = new BufferedReader(fr);
        String strLine = "";

        try {
            while((strLine = br.readLine()) != null) {
                sb.append(strLine);
                sb.append("\n");
            }
        } catch (IOException var17) {
            var17.printStackTrace();
        } finally {
            try {
                fr.close();
                br.close();
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return sb.toString();
    }
}

以上是一些依赖和方法用于测试的过程。
以下是写正式业务功能;

@RequestMapping(name = "协议详情模板数据导出", value = "/v1/exportTempExcel", method = RequestMethod.GET)
    public JsonResult exportTempExcel(ExportXmlAndCsvDTO dto, HttpServletResponse response) throws UnsupportedEncodingException {
        //随机数
        String random = RandomUtil.randomNumbers(6);
        String separetor = File.separator;
        String resource = GeneralXML.class.getResource(separetor + "opcTemplate.xml").getPath();
        String parent = new File(resource).getParent() + separetor + "opcConfig" + separetor;
        String xmlPath = parent + random + "opc.xml";
        String csvPath = parent + "pointFile" + separetor + random + ".csv";
        List<PointInfoExportCSV> pointinfoList = clagreementInfoService.getPointByParentId(dto);
        //开始组装xml数据
        GeneralXML generalXML = new GeneralXML();
        String s = GeneralXML.readFileByer(resource);
        MessageFormat mf = new MessageFormat(s);
        StringBuffer sb = new StringBuffer();
        sb.append(generalXML.head);
        sb.append(generalXML.root_start);
        sb.append(mf.format(new Object[]{" ", " ", " ", " ", " ", " ", " ", separetor + "opcConfig" + separetor + "pointFile" + separetor + random + ".csv"}));
        sb.append(generalXML.root_end);
        Document document = XmlUtil.parseXml(sb.toString());
        XmlUtil.toFile(document, xmlPath);
        //组装xml结束
        //开始组装csv数据
        CsvWriter writer = CsvUtil.getWriter(csvPath, CharsetUtil.CHARSET_UTF_8);
        Field[] declaredFields = PointInfoExportCSV.class.getDeclaredFields();
        //获取字段名字
        List<String> fieldName = Arrays.stream(declaredFields).sequential().map(fi -> fi.getName()).collect(Collectors.toList());
        //把数据转成map类型用于组装数据使用
//        List<Map> sourMap = pointinfoList.stream().map(po -> JSONUtil.toBean(JSONUtil.toJsonStr(po), Map.class)).collect(Collectors.toList());
        List<String[]> sourceList = pointinfoList.stream().map(po -> po.toString().split(",")).collect(Collectors.toList());
        List<Object> resultList = new ArrayList<>();
        //添加第一行为标题;
        resultList.add(fieldName);
        //把数据放入list里面
        resultList.addAll(sourceList);
        writer.write(resultList);
        //组装csv结束
        File zip = ZipUtil.zip(parent);
        //写出到浏览器
        downloadFile(response, zip);
        //删除zip
        FileUtil.del(zip);
        //删除路径文件
        FileUtil.del(parent);
        return success();
    }
 /***
     * 用于浏览器下载文件
     * @param response
     * @param zip
     * @throws UnsupportedEncodingException
     */
    private void downloadFile(HttpServletResponse response, File zip) throws UnsupportedEncodingException {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zip.getName(), "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = FileUtil.getInputStream(zip);
        byte[] buffer = new byte[1024];
        try (OutputStream os = response.getOutputStream()) {
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值