java 将查询到的sql结果导出为csv文件

1.引入javacsv.jar包

maven引入:https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv/2.0

<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
    <groupId>net.sourceforge.javacsv</groupId>
    <artifactId>javacsv</artifactId>
    <version>2.0</version>
</dependency>

2.代码

    /**
     *
     * @param defiled_info sql查询结果
     * @param fileName fileName为下载文件名,防止文件重名覆盖,可加入时间戳
     */
    public static void defiled_csv(List<HashMap<String, Object>> defiled_info,String fileName) {
        String rootPath = "";
        if(fileName == null){
            rootPath = "D:/file_"+ System.currentTimeMillis()+".csv";
        }else {
            rootPath = "D:/"+fileName+System.currentTimeMillis()+".csv";
        }
        //第一个参数为文件存储路径,第二个为指定导出的文件字段间的间隔符,第三个参数为转出编码
        CsvWriter csvWriter = new CsvWriter(rootPath, '|', Charset.forName("GBK"));
        //需要确保查询的结果不能为空,也可以在这做判断,不为空才能自动取表头,不然需要手动传入表头
        HashMap<String, Object> hashMap = defiled_info.get(0);
        Set<String> defiled_sets = hashMap.keySet();
        try {
            if (defiled_sets.size() > 0) {
                for (String key : defiled_sets) {
                    //写入表头信息
                    csvWriter.write(key, false);
                }
                //换行
                csvWriter.endRecord();
            }
            //写入类容信息
            for (int k = 0; k < defiled_info.size(); k++) {
                HashMap<String, Object> infos = defiled_info.get(k);
                for (String key : defiled_sets) {
                    //如果某字段为空,这转义为字符串"null"
                    if(infos.get(key) == null){
                        csvWriter.write("null");
                    }else {
                        csvWriter.write(infos.get(key).toString());
                    }
                }
                csvWriter.endRecord();
            }
            //关闭流
            csvWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值