实用的csv生成导出,欢迎大佬改进!

最近遇到一个需求,需要生成csv格式的文件!

开始百度找案例

百度上的案例好多都是以map形式的保存导出数据,一般项目中都是使用使用List<实体类>进行数据返回导出的,找了好久终于东拼西凑出来一段能用的但不是那么优雅的代码。

欢迎大佬进行优化!

/**
 * csv导入导出工具类
 *
 * @desc
 */
public class CsvUtils {
    private static Logger logger = LoggerFactory.getLogger(CsvUtils.class);

    /**
     * 导出生成csv文件
     *
     * @param response
     * @param fileName 文件名称
     * @throws IOException
     */
    public static <T> CommonResult<String> exportFile(HttpServletResponse response, String[] titles, List<T> list, String fileName) {
        String csvFilePath = "E:/";
        String path = "";
        String name = "";
        /**
         * 生成csv文件
         * */
        try {
            File file = new File(csvFilePath);
            if (!file.exists()) {
                file.mkdir();
            }
            long time = new Date().getTime();
            path = csvFilePath + fileName + time + ".csv";
            name = fileName + time + ".csv";
            File cvsFile = new File(path);
            if (!cvsFile.exists()) {
                file.mkdir();
            }
            boolean isFirst = true;
            BufferedWriter out;
            //构建输出流
            out = new BufferedWriter(new FileWriter(cvsFile));
            //csv文件是逗号分隔,除第一个外,每次写入一个单元格数据后需要输入逗号
            for (String title : titles) {
                out.write(title);
                out.write(",");
            }
            //写内容
            for (T t : list) {
                StringBuilder sb2 = new StringBuilder();
                Class clazz = (Class) t.getClass();
                Field[] fs = clazz.getDeclaredFields();
                for (int i = 0; i < fs.length; i++) {
                    Field f = fs[i];
                    f.setAccessible(true);
                    try {
                        Object val = f.get(t);
                        if (val == null) {
                            sb2.append("");
                        } else {
                            sb2.append(val.toString() + "\t");
                        }
                        sb2.append(",");
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        logger.info("生成文件异常");
                        logger.info(ExceptionUtils.getStackTrace(e));
                    }
                }
                if (isFirst) {
                    isFirst = false;
                    out.newLine();
                }
                out.write(sb2.toString());
                out.newLine();
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.info("生成文件异常");
            logger.info(ExceptionUtils.getStackTrace(e));
        }
        /**
         * 下载文件
         * */
        InputStream in = null;
        OutputStream out = null;
        try {
            response.setContentType("application/csv;charset=UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            in = new FileInputStream(path);
            int len = 0;
            byte[] buffer = new byte[1024];
            response.setCharacterEncoding("UTF-8");
            out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            logger.info("下载文件异常");
            logger.info(ExceptionUtils.getStackTrace(e));
        } catch (IOException e) {
            logger.info("下载文件异常");
            logger.info(ExceptionUtils.getStackTrace(e));
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                logger.info("下载文件异常");
                logger.info(ExceptionUtils.getStackTrace(e));
                throw new RuntimeException(e);
            }

        }
        deleteFile(csvFilePath, name);
        return null;
    }

    /**
     * 删除临时文件
     *
     * @param filePath 文件目录路径
     * @param fileName 文件名称
     */
    public static void deleteFile(String filePath, String fileName) {
        File file = new File(filePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile() && fileName != null && fileName.equals(files[i].getName())) {
                    files[i].delete();
                    return;
                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值