Java csv导出下载

主要用于页面直接下载csv。

上代码 !

serviceImpl:

 public void deviceExportExcel(HttpServletResponse response) throws Exception {
        
        //表头
        Map<String, String> header = new LinkedHashMap<>();
        header.put("name", "名字");
        header.put("age", "年龄");
        header.put("sex", "性别");
    
        //结构数据
        List<Map<String,String>> dataList = new ArrayList<>();  //组装自己的数据。
        //例:
              Map<String,String> map = new HashMap<>();
              map.put("name","张三");
              map.put("age","20");  
              map.put("sex","男");  
              dataList.add(map);
              ap<String,String> map1 = new HashMap<>();
              map1.put("name","李四");
              map1.put("age","21");  
              map1.put("sex","男");  
              dataList.add(map1);

        CsvUtils.write(response,header,dataList);
    }

工具类:CsvUtils

import com.csvreader.CsvWriter;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;


public class CsvUtils {

    public static void write(HttpServletResponse response,Map<String, String> header,List<Map<String,String>> dataList){
        try {
            //创建临时csv文件
            File tempFile = createTempFile(header,dataList);
            //输出csv流文件,提供给浏览器下载
            outCsvStream(response, tempFile);
            //删除临时文件
            deleteFile(tempFile);

        } catch (IOException e) {
            System.out.println("导出失败");
        }
    }

    public static File createTempFile(Map<String, String> header,List<Map<String, String>> datas) throws IOException {
        File tempFile = File.createTempFile("vehicle", ".csv");
        CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(), ',', Charset.forName("UTF-8"));
        // 写表头
        List<String> nameList = new ArrayList<>();
        Set<String> strings = header.keySet();
        for (String srt : strings){
            nameList.add(header.get(srt));
        }
        String[] headers = StringUtils.join(nameList,",").split(",");
        csvWriter.writeRecord(headers);
        for (Map<String,String> data : datas) {
            //这里如果数据不是String类型,请进行转换
            for (String srt : strings){
                String s =data.get(srt);
                csvWriter.write(s);
            }
            csvWriter.endRecord();
        }
        csvWriter.close();
        return tempFile;
    }
    /**
     * 写入csv结束,写出流
     */
    public static void outCsvStream(HttpServletResponse response, File tempFile) throws IOException {
        java.io.OutputStream out = response.getOutputStream();
        byte[] b = new byte[10240];
        java.io.File fileLoad = new java.io.File(tempFile.getCanonicalPath());
        response.reset();
        response.setContentType("application/csv");
        response.setHeader("content-disposition", "attachment; filename=export.csv");
        java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);
        int n;
        //为了保证excel打开csv不出现中文乱码
        out.write(new   byte []{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
        while ((n = in.read(b)) != -1) {
            //每次写入out1024字节
            out.write(b, 0, n);
        }
        in.close();
        out.close();
    }

    /**
     * 删除单个文件
     *
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile( File file) {
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static BigDecimal getNumbersSum(String a) {
        BigDecimal c = new BigDecimal(a);
        //与参数相等返回0、小于参数返回 -1、大于参数返回 1。
        return c.compareTo(new BigDecimal("0.00000000")) == 0 ? new BigDecimal("0") : c;
    }


}

结果:

注:也是边学边写,如有错误请指出,有不懂的,可留言,互相交流学习。

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值