欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot框架中-java实现Excel、csv、txt 文件的批量导出数据-亲手实测(二)-csv & txt

程序员文章站 2024-03-20 21:27:04
...

接上文的Excel导出,有朋友在评论找其他两种的,才想起更新来,下面直接贴出csv和 txt导出的代码:

参数说明,如果有不明白的可以参考excel导出,或者直接下方评论:

  1. rows:为从数据库中查询出的结果集合,我这里并没有拿实体类作映射,其结构见后面贴的图;

  2. filePathAndName:文件下载路径,返回给前端,打开便直接下载;

  3. file:存于服务端目录的相对路径;

private JsonResult exportCsv(List<Map> list, File file, String result) { //导出csv文件
    try {
        log.info("filepath:" + file.getPath());
        file.createNewFile();
        FileOutputStream stream;// provides file access
        OutputStreamWriter writer;// writes to the file
        stream = new FileOutputStream(file);
        writer = new OutputStreamWriter(stream, "gb2312");

        //首行
        Iterator<Map> iterator = list.iterator();
        Map map = iterator.next();
        Set set = map.keySet(); //col 集合
        Iterator iterator1 = set.iterator();
        while (iterator1.hasNext()) {
            writer.write(iterator1.next() + ",");
        }

        //第二行开始都是数据
        Iterator<Map> iterator2 = list.iterator(); //这个地方不要用上面的iterator,切记,会从第二条数据开始写
        while (iterator2.hasNext()) {
            writer.write("\r\n"); //回车 进入下一行
            Map map1 = iterator2.next();
            Set<String> set1 = map.keySet();
            Iterator it = set1.iterator();
            while (it.hasNext()) {
                Object o = map1.get(it.next() + "");
                writer.write(o + ","); //逗号在csv文件中相当于tab键 同一行内 右移一个单元格的作用
            }
        }
        writer.close();
        stream.close();
        return JsonResult.success(result);
    } catch (Exception e) {

        e.printStackTrace();
        return JsonResult.fail("下载失败");
    }
}

简单粗暴点 txt:

private JsonResult exportTxt(List<Map> list, File file, String result) {

    log.info("filepath:" + file.getPath());
    try {
        file.createNewFile();
        FileOutputStream stream;// provides file access
        OutputStreamWriter writer;// writes to the file
        stream = new FileOutputStream(file);
        writer = new OutputStreamWriter(stream, "gb2312");

        //写首行
        Iterator<Map> iterator = list.iterator();
        Map map = iterator.next();
        Set set = map.keySet(); //col 集合
        Iterator iterator1 = set.iterator();
        while (iterator1.hasNext()) {
            writer.write(iterator1.next() + ",");
        }

        Iterator<Map> iterator2 = list.iterator(); //这个地方不要用上面的iterator,切记,会从第二条数据开始写
        //第二行开始都是数据
        while (iterator2.hasNext()) {
            writer.write("\r\n");
            Map map1 = iterator2.next();
            Iterator it = set.iterator();
            while (it.hasNext()) {
                Object o = map1.get(it.next() + "");
                writer.write(o + ",");
            }
        }
        writer.close();

        return JsonResult.success(result);
    } catch (Exception e) {
        e.printStackTrace();
        return JsonResult.fail("下载失败");
    }
}