Java生成CSV工具类

package com.test.app.utils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

/**
 * @Description: CSV生成工具类
 * @Author: hunger.zhu
 * @CreateDate: 2019/4/10 15:21
 */
public class CsvUtils {

    private static final Logger logger = LoggerFactory.getLogger(CsvUtils.class);

    /**
     * 写出CSV文件,每一行数据为一个Object对象
     * @param data  List<Object>
     * @param header    第一行标题
     * @param filePath  写出文件的绝对路径
     * @param split     CSV文件分隔符,一般为","
     * @throws Exception
     */
    public static void writeCSV(List<?> data, List<String> header, String filePath, String split) throws Exception {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
            // 填充对象属性值
            if (!CollectionUtils.isEmpty(header)) {
                // 添加头部(首行)
                for (int i = 0; i < header.size(); i++) {
                    bw.append(header.get(i));
                    if (i != header.size() - 1) {
                        bw.append(split);
                    }
                }
                bw.newLine();
            }
            // 填充数据
            if (!CollectionUtils.isEmpty(data)) {
                Class<? extends Object> objClass = data.get(0).getClass();
                Field[] fields = objClass.getDeclaredFields();
                for (int i = 0; i < data.size(); i++) {
                    for (int j = 0; j < fields.length; j++) {
                        Method[] methods = objClass.getDeclaredMethods();
                        for (Method method : methods) {
                            if (method.getName().equalsIgnoreCase("get" + fields[j].getName())) {
                                String property = (String) method.invoke(data.get(i), null);
                                bw.append(property == null ? "" : property);
                                break;
                            }
                        }
                        if (j != fields.length - 1) {
                            bw.append(split);
                        }
                    }
                    if (i != data.size() - 1) {
                        bw.newLine();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Write CSV exception------", e);
            throw e;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    logger.error("Close OutputStream exception------", e);
                }
            }
        }
    }

    /**
     * 写出CSV文件,每一行数据为一个List<String>集合
     * @param data  List<String>
     * @param header    第一行标题
     * @param filePath  写出文件的绝对路径
     * @param split     CSV文件分隔符,一般为","
     * @throws Exception
     */
    public static void writeCSVFromList(List<List<String>> data, List<String> header, String filePath,
                                        String split) throws Exception {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
            // 填充对象属性值
            if (!CollectionUtils.isEmpty(header)) {
                // 添加头部(首行)
                for (int i = 0; i < header.size(); i++) {
                    bw.append(header.get(i));
                    if (i != header.size() - 1) {
                        bw.append(split);
                    }
                }
                bw.newLine();
            }
            // 填充数据
            if (!CollectionUtils.isEmpty(data)) {
                for (int i = 0; i < data.size(); i++) {
                    List<String> list = data.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        bw.append(list.get(j));
                        if (j != list.size() - 1) {
                            bw.append(split);
                        }
                    }
                    if (i != data.size() - 1) {
                        bw.newLine();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Write CSV exception------", e);
            throw e;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    logger.error("Close OutputStream exception------", e);
                }
            }
        }
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值