工具类--Java生成csv文件代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/smd2575624555/article/details/78725018

工具类CreateCSVUtilsJava生成csv文件代码

Csv文件支持excel文件格式打开,但是却不需要poi的支持,文件生成更加简单,方便,可功能却不如poi那样的强大

下面是生产CSV文件的代码

主要分成两个两个类

1.类是常量抽取形成类,便于改动不影响工具类

2.生成csv文件工具类

*会使用到joda-time的jar,下载解压就好

常量类FileConstantUtilsp

package com.boss.util;

import java.io.File;
import java.util.Arrays;
import java.util.List;


/**
 * CSV常量工具类
 */
public class FileConstantUtils {

    public final static List<Object>   MEASURE_HEAD_LIST   = Arrays.asList(
            "客户ID",
            "产品ID",
            "产品类型"
    );

    // 导出文件路径
    public final static String  DOWNLOAD_FILE_PATH  = "D:" + File.separator + "csv" + File.separator + "download" + File.separator;
    public final static String FILE_NAME = "存疑报表";
}

工具类CreateCSVUtils 

package com.kscloud.boss.charge.util;

import org.joda.time.DateTime;
import java.io.*;
import java.util.List;
import java.util.Locale;

public class CreateCSVUtils {
    /**
     * 创建CSV文件类型
     * @param dataLists
     * @return
     */

    public static File createCSVFile( List<Object> dataLists, List<Object>   headList) throws IOException {

        File csvFile = null;
        BufferedWriter csvWrite = null;
        DateTime dateTime=new DateTime();
        String stringDate = dateTime.toString("yyyy年MM月dd日HH时mm分ss秒", Locale.CHINESE);
        try {

            //定义文件类型
            csvFile = new File(FileConstantUtils.DOWNLOAD_FILE_PATH + File.separator + FileConstantUtils.FILE_NAME +stringDate+ ".csv");
            //去文件目录
            File parent = csvFile.getParentFile();
            if (parent.exists()) {
                parent.mkdirs();

            }

            //创建文件
            csvFile.createNewFile();
            csvWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);

            //写入表头
            write(headList, csvWrite);
            //写入数据

            for ( Object dataList:dataLists){
            write((List<Object>)dataList, csvWrite);
            }
            csvWrite.flush();
        } catch (IOException e) {
            throw  new IOException("文件生成失败");
        } finally {

            try {
                csvWrite.close();

            } catch (IOException e) {

                throw  new IOException("关闭文件流失败");
            }
        }

        return csvFile;
    }



    /**
     * 将数据按行写入数据
     *
     * @param dataList
     * @param csvWreite
     * @throws IOException
     */
    private static void write(List<Object> dataList,BufferedWriter csvWreite) throws IOException {

        for (Object data: dataList) {
            StringBuffer buffer=new StringBuffer();
            String rowStr=buffer.append("\"").append(data).append("\",").toString();
            csvWreite.write(rowStr);
//            csvWreite.newLine();
        }
        csvWreite.newLine();
    }

}

 

展开阅读全文

没有更多推荐了,返回首页