java将表数据导出CSV文件以及读取和写入CSV文件

java将表数据导出CSV文件

 @Autowired
    UserServiceImpl userService;
    @Test
    void CSV(){
       List<User> userList =  userService.list();

        exportCsv1(userList);

    }
    //封装参数
    private static List<List<Object>> getNovel1(List<User> userList) {

        List<List<Object>> dataList = new ArrayList<List<Object>>();
        List<Object> rowList = null;
        for (int i = 0; i < userList.size(); i++){
            User user = userList.get(i);
            int id = Math.toIntExact(user.getId());
            String name = user.getName();
            int age = user.getAge();
            String emal = user.getEmail();
            rowList = new ArrayList<Object>();
            Object[] row = new Object[4];
            row[0] = id;
            row[1] = name;
            row[2] = age;
            row[3] = emal;
            for (int j = 0; j < row.length; j++) {
                rowList.add(row[j]);
            }
            dataList.add(rowList);
        }
        return dataList;
    }

    //初始化表格
    public static void exportCsv1(List<User> userList) {
        long startTime = System.currentTimeMillis();
        // 设置表格头
        Object[] head = {"id", "姓名", "年龄", "邮件"};
        List<Object> headList = Arrays.asList(head);
        // 设置数据
        List<List<Object>> dataList = getNovel1(userList);
        // 导出文件路径
        String downloadFilePath = "E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile";
        // 导出文件名称
        String fileName = "download1";
        // 导出CSV文件
        File csvFile = createCSVFile1(headList, dataList, downloadFilePath, fileName);
        String fileName2 = csvFile.getName();
        System.out.println(fileName2);
        long endTime = System.currentTimeMillis();
        System.out.println("整个CSV导出" + (endTime - startTime)+"毫秒");
    }


    /**
     * CSV文件生成方法
     * @param head
     * @param dataList
     * @param outPutPath
     * @param filename
     * @return
     */
    public static File createCSVFile1(List<Object> head, List<List<Object>> dataList, String outPutPath, String filename) {
        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv");
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
            // 写入文件头部
            writeRow1(head, csvWtriter);

            // 写入文件内容
            for (List<Object> row : dataList) {
                writeRow1(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据方法
     * @param row
     * @param csvWriter
     * @throws IOException
     */
    private static void writeRow1(List<Object> row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuffer buf = new StringBuffer();
            String rowStr = buf.append("\"").append(data).append("\t\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }

读取和写入

package com.xc.mybatisplus3boot.until;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetCSVInfo {

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream("E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile\\download.csv"),"UTF-8"));
        try {
            reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉
            String line = null;
            List it = new ArrayList();

            while((line=reader.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分

                String a = item[item.length-1];//这就是你要的数据了
                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值

                // 正则表达式去掉String特殊字符
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(a);
                String s = m.replaceAll("");
                it.add(s);
            }
            it.forEach(System.out::println);

            /**
             * 在CSV中追加数据
             */
            File csv = new File("E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile\\download1.csv"); // CSV数据文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true));
            for (Object a:it) {
                // \n 换行
                bw.write((String) a + "\n");
            }
            bw.newLine();
            bw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}

读取指定行数 这个不错

package com.xc.mybatisplus3boot.until;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CSVTest {

    public static String[] getTxtContent(String path){

        File f = null;
        String[] a = null;
        a = new String[100000];
        f=new File(path);
        try {
            InputStreamReader read = new InputStreamReader(new FileInputStream(f), "GBK");
            BufferedReader reader = new BufferedReader(read);
            String line;
            int i;
            for (i = 0; i < 100000; i++){
                if ((line = reader.readLine()) != null){
                    a[i] = line;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
            return a;
    }
    public static String listTxtByRow1(String path, Integer row){
        String[] s = getTxtContent(path);
        return "第"+row+"行:"+s[row-1];

    }
    public static String listCSVAll(String path){
        String[] s = getTxtContent(path);
        List<String> list = new ArrayList();
        for (String info: s) {
            if (info == null || info.equals("")){

            }else {
                list.add(info);
            }
        }
        return "全部数据:"+list;

    }

    public static List<String> listTxtByRow2(String path, Integer start, Integer end){
        List<String> list =new ArrayList<String>();
        String[] s = getTxtContent(path);
        for(int i = start;i <= end;i++){
            list.add(s[i-1]);
        }
        return list;


    }

    public static void main(String[] args) {
        System.out.println(listCSVAll("F:\\fileTest\\dadada.csv")); // 获取全部数据
        System.out.println(listTxtByRow1("F:\\fileTest\\dadada.csv",1));//取出第1行数据
        System.out.println("==================取出指定行数=====================");
        List<String> list = listTxtByRow2("F:\\fileTest\\dadada.csv", 2, 5);//取出2-5行数据
        for(int i = 0;i<list.size();i++){
            System.out.println(list.get(i));
        }

    }


}

追加写入

package com.xc.mybatisplus3boot.until;

import java.io.*;

public class writeCSV {

    public static void main(String[] args) {
        try {
//            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile\\download1.csv"),"UTF-8")); // 附加
            File csv = new File("E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile\\download1.csv"); // CSV数据文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true));
            // 添加新的数据行
            bw.write("10"+"," +"李四" + "," + "1988" + "," + "1992");

            bw.newLine();
            bw.close();

        } catch (FileNotFoundException e) {
            // File对象的创建过程中的异常捕获
            e.printStackTrace();
        } catch (IOException e) {
            // BufferedWriter在关闭对象捕捉异常
            e.printStackTrace();
        }
    }

}

追加写入和读取

package com.xc.mybatisplus3boot.until;

import com.csvreader.CsvReader;
import org.yaml.snakeyaml.reader.UnicodeReader;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetCSVInfo {

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream("F:\\fileTest\\dadada.csv"),"UTF-8"));
        try {
            reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉
            String line = null;
            List it = new ArrayList();

            while((line=reader.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分

                String a = item[item.length-1];//这就是你要的数据了
                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值

                // 正则表达式去掉String特殊字符
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(a);
                String s = m.replaceAll("");
                it.add(s);

            }
            it.forEach(System.out::println);

            /**
             * 在CSV中追加数据
             */
            File csv = new File("E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile\\download1.csv"); // CSV数据文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true));
            for (Object a:it) {
                // \n 换行
                bw.write((String) a + "\n");
            }
            bw.newLine();
            bw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}

写入

package com.xc.mybatisplus3boot.until;


import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


public class CSVUtil {
    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_RN = "\r\n";

    public static void main(String[] args) {
        exportCsv();
    }

    //封装参数
    private static List<List<Object>> getNovel() {

        List<List<Object>> dataList = new ArrayList<List<Object>>();
        List<Object> rowList = null;
        for (int i = 0; i < 5; i++) {
            rowList = new ArrayList<Object>();
            Object[] row = new Object[4];
            row[0] = i;
            row[1] = "风云第一刀" + i + System.lineSeparator() + "风云第一刀999";
            row[2] = "古龙" + i + "";
            row[3] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            for (int j = 0; j < row.length; j++) {
                rowList.add(row[j]);
            }
            dataList.add(rowList);
        }
        return dataList;
    }

    //初始化表格
    public static void exportCsv() {
        long startTime = System.currentTimeMillis();
        // 设置表格头
        Object[] head = {"id", "姓名", "年龄", "邮件"};
        List<Object> headList = Arrays.asList(head);
        List<List<Object>> dataList = getNovel();
        // 导出文件路径
        String downloadFilePath = "E:\\mysql5.7.31\\mysql-5.7.31-winx64\\outFile";
        // 导出文件名称
        String fileName = "download1";
        // 导出CSV文件
        File csvFile = CSVUtil.createCSVFile(headList, dataList, downloadFilePath, fileName);
        String fileName2 = csvFile.getName();
        System.out.println(fileName2);
        long endTime = System.currentTimeMillis();
        System.out.println("整个CSV导出" + (endTime - startTime)+"毫秒");
    }


    /**
     * CSV文件生成方法
     * @param head
     * @param dataList
     * @param outPutPath
     * @param filename
     * @return
     */
    public static File createCSVFile(List<Object> head, List<List<Object>> dataList, String outPutPath, String filename) {
        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(outPutPath + File.separator + filename + ".csv");
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
            // 写入文件头部
            writeRow(head, csvWtriter);

            // 写入文件内容
            for (List<Object> row : dataList) {
                writeRow(row, csvWtriter);
            }
            csvWtriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 写一行数据方法
     * @param row
     * @param csvWriter
     * @throws IOException
     */
    private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (Object data : row) {
            StringBuffer buf = new StringBuffer();
            String rowStr = buf.append("\"").append(data).append("\t\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }

}

写入user字段和字段类型 比较好 但是无追加方法,获取某行、某列、某行某列的数据

测试类
参考文档

package com.xc.mybatisplus3boot.until.CSV;
;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * @author:
 * @description:    测试类
 * @date Create in 2018/12/24 15:22
 * @modified By:
 */
public class Demo {

    private  static Logger log = LoggerFactory.getLogger(Demo.class);
    static String filePath = "F:\\fileTest\\dadada.csv";
    public static void main(String[] args){

        CsvConfig csvConfig = new CsvConfig("gbk","yyyy-MM-dd HH:mm:ss:SSS",',');
        CsvUtil csvUtil = new CsvUtil();

//        //写文件代码
//        User user = new User(2L,"lsls",12,"lslssl");
//        User user1 = new User(3L, "M", 22, "ssssss");
//        ArrayList<User> users = new ArrayList<>(3);
//        users.add(user);
//
//        users.add(user1);
//        csvUtil.writeFile(filePath, users, User.class,csvConfig);
//
//        //读文件代码  以实体类对象输出
//        try {
//            List<User> objects = csvUtil.readFile(filePath, User.class,csvConfig);
//            if(CollectionUtils.isEmpty(objects)){
//                log.info("====没有从文件{}获取到值====",filePath);
//            }
//            log.debug("==获取的结果总数:{}",objects.size());
//            log.debug("==获取的结果:{}", JSON.toJSONString(objects));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


        /**
         * 和CSV表结构一样 换行
         */
        File csv = new File(filePath); // CSV文件路径
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(csv));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line = "";
        String everyLine = "";
        try {
            List<String> allString = new ArrayList<>();
            while ((line = br.readLine()) != null) // 读取到的内容给line变量
            {
                everyLine = line;
                System.out.println(everyLine);
                allString.add(everyLine);
            }
            System.out.println("csv表格中所有行数:" + allString.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
//
//        test(3,2);
        testCol(2);
//
    }


    /**
     * 获取某列的数据
     * @param col
     */
    private static void testCol(int col) {
        try {
            BufferedReader reade = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null;
            int index=0;
            reade.readLine(); //注释掉 第一行表头信息
            while((line=reade.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分

                    if(item.length>=col){
                        String last = item[col-1];//这就是你要的数据了
                        System.out.println(last);
                    }

                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取第几行,第几列的数据
     * @param row
     * @param col
     */
    static void test(int row, int col){
        try {
            BufferedReader reade = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null;
            int index=0;
            while((line=reade.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
                if(index==row-1){
                    System.out.println(item.length);
                    if(item.length>=col-1){
                        String last = item[col-1];//这就是你要的数据了
                        System.out.println(last);
                    }
                }
                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

user

package com.xc.mybatisplus3boot.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;

import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 
 * </p>
 *
 * @author ls
 * @since 2021-06-16
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class User{


    /**
     * 主键ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 邮箱
     */
    private String email;


}

UserColumns

package com.xc.mybatisplus3boot.pojo;

import lombok.Data;

@Data
public class UserColumns {
    private String columns;
    private String type;
    private String tbName;
}

CsvConfig

package com.xc.mybatisplus3boot.until.CSV;
/**
 * @author:
 * @description:    工具配置类
 * @date Create in 2018/12/26 10:09
 * @modified By:
 */
public class CsvConfig {

    /** 字符编码 */
    private String charset;
    /** 日期格式 */
    private String dateFormat;
    /** 分隔符 */
    private char separator;

    public CsvConfig(){

    }
    public CsvConfig(String charset, String dateFormat, char separator){
        this.charset = charset;
        this.dateFormat = dateFormat;
        this.separator = separator;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public String getDateFormat() {
        return dateFormat;
    }

    public void setDateFormat(String dateFormat) {
        this.dateFormat = dateFormat;
    }

    public char getSeparator() {
        return separator;
    }

    public void setSeparator(char separator) {
        this.separator = separator;
    }
}

CsvUntil
如果CSV第二行有字段类型,则报错

package com.xc.mybatisplus3boot.until.CSV;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.xc.mybatisplus3boot.pojo.UserColumns;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author:
 * @description: 提供csv文件的操作方法
 * @date Create in 2018/12/24 15:01
 * @modified By:
 */

public class CsvUtil {

    private  final Logger log = LoggerFactory.getLogger(CsvUtil.class);

    /**
     * 读取csc文件
     *
     * @param filePath      文件路径
     * @param clazz         指定类型
     * @param csvConfig     配置信息
     * @return              读取结果
     */

    public  <T> List<T> readFile(String filePath, Class<T> clazz, CsvConfig csvConfig) throws Exception {
        if (null == filePath || null == clazz) {
            return null;
        }
        List<T> result = new ArrayList<>(10);
        this.checkCsvConfig(csvConfig);
        CsvReader reader = new CsvReader(filePath, csvConfig.getSeparator(), Charset.forName(csvConfig.getCharset()));

        //获取类方法
        Map<Field, Method> methods = new HashMap<>(11);
        Field[] fields = clazz.getDeclaredFields();
        if (fields == null) {
            log.error("========未获取到类{}的属性值,请确认类{}是否传入正确========", clazz.getName(), clazz.getName());
            return null;
        }
        for (int i = 0; i < fields.length; i++) {
            String methodName = "set" + fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1);
            Method method = clazz.getMethod(methodName, fields[i].getType());
            if (method == null) {
                log.info("====类{}中没有属性{}的set方法,请确定是否实现====", clazz.getName(), fields[i].getName());
                continue;
            }
            methods.put(fields[i], method);
        }
        //跳过头文件
        reader.readHeaders();
        String[] headers = reader.getHeaders();
        if(null == headers || headers.length <=0){
            log.error("========文件< {} >缺少数据头,请增加数据头到文件========",filePath);
            return null;
        }
        while (reader.readRecord()) {
            T obj = (T)clazz.newInstance();
            Set<Field> keys = methods.keySet();
            for (Field key : keys) {
                key.setAccessible(true);
                String value = reader.get(key.getName());
                if(StringUtils.isBlank(value)){
                    continue;
                }
                switch (key.getType().getSimpleName()) {
                    case "Integer":
                        methods.get(key).invoke(obj,Integer.valueOf(value));
                        break;
                    case "String":
                        methods.get(key).invoke(obj,value);
                        break;
                    case "Boolean":
                        methods.get(key).invoke(obj,Boolean.valueOf(value));
                        break;
                    case "Long":
                        methods.get(key).invoke(obj,Long.valueOf(value));
                        break;
                    case "Float":
                        methods.get(key).invoke(obj,Float.valueOf(value));
                        break;
                    case "Double":
                        methods.get(key).invoke(obj,Double.valueOf(value));
                        break;
                    case "Date":
                        try {
                            methods.get(key).invoke(obj,new SimpleDateFormat(csvConfig.getDateFormat()).parse(value));
                            break;
                        } catch (ParseException e) {
                            log.info("====日期转换失败,使用的日期格式为:{},与给定的日期数据格式不匹配,请重新指定日期转换格式====",csvConfig.getDateFormat());
                            log.info("====错误原因:{}",e);
                            throw new RuntimeException(e);
                        }
                    default:
                        methods.get(key).invoke(obj,value);
                        break;
                }
            }
            result.add(obj);
        }
        reader.close();
        return result;
    }

    /**
     * 读取csc文件
     * 默认编码格式是本地编码格式
     * @param filePath      文件路径
     * @param separator     分隔符
     * @param t             指定类型
     * @return              读取结果
     */
    public  <T> List<T> readFile(String filePath, char separator, Class<T> t) throws Exception {
        return this.readFile(filePath,t,this.initCsvConfig());
    }

    /**
     * 把缓存内容写入到csv文件
     *
     * @param filePath       文件路径
     * @param cacheContainer 缓存容器
     * @param csvConfig      配置信息
     * @return 写入是否成功
     */
    public <T> boolean writeFile(String filePath, List<T> cacheContainer, Class<T> t,CsvConfig csvConfig) {
        if (StringUtils.isBlank(filePath) || CollectionUtils.isEmpty(cacheContainer) || null == t) {
            return false;
        }
        this.checkCsvConfig(csvConfig);
        CsvWriter writer = new CsvWriter(filePath, csvConfig.getSeparator(), Charset.forName(csvConfig.getCharset()));
        //获取实体类中的属性
        Field[] fields = t.getDeclaredFields();
        //生成数据头
        String[] headers = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            headers[i] = fields[i].getName();
        }

        System.out.println("=========");
        for (String header : headers) {
            System.out.println(header);
        }
        System.out.println("=========");

        String[] columnsType = new String[fields.length];
        //写入到文件
        try {
            writer.writeRecord(headers);
            writer.writeRecord(columnsType);
            for (T obj : cacheContainer) {
                String[] str = coverFieldsValue(obj,csvConfig);
                writer.writeRecord(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        writer.close();
        return true;
    }
    /**
     * 把缓存内容写入到csv文件
     * 带有字段类型
     *
     * @param filePath       文件路径
     * @param cacheContainer 缓存容器
     * @param csvConfig      配置信息
     * @return 写入是否成功
     */
    public <T> boolean writeFileAndType(String filePath, List<T> cacheContainer, Class<T> t, List<UserColumns> columnsList,CsvConfig csvConfig) {
        if (StringUtils.isBlank(filePath) || CollectionUtils.isEmpty(cacheContainer) || null == t) {
            return false;
        }
        this.checkCsvConfig(csvConfig);
        CsvWriter writer = new CsvWriter(filePath, csvConfig.getSeparator(), Charset.forName(csvConfig.getCharset()));
        //获取实体类中的属性
        Field[] fields = t.getDeclaredFields();
        //生成数据头
        String[] headers = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            headers[i] = fields[i].getName();
        }

        System.out.println("=========");
        for (String header : headers) {
            System.out.println(header);
        }
        System.out.println("=========");

        String[] columnsType = new String[fields.length];
        // 获取字段类型
        for (int i = 0;i<columnsList.size();i++) {
            columnsType[i] = columnsList.get(i).getType();
        }
        System.out.println("=========");
        for (String ct : columnsType) {
            System.out.println(ct);
        }
        System.out.println("=========");
        //写入到文件
        try {
            writer.writeRecord(headers);
            writer.writeRecord(columnsType);
            for (T obj : cacheContainer) {
                String[] str = coverFieldsValue(obj,csvConfig);
                writer.writeRecord(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        writer.close();
        return true;
    }

    /**
     * 把缓存内容写入到csv文件
     * 默认编码格式是本地编码格式
     * @param filePath       文件路径
     * @param cacheContainer 缓存容器
     * @return 写入是否成功
     */
//    public <T> boolean writeFile(String filePath, List<T> cacheContainer, Class<T> t) {
//        return this.writeFile(filePath,cacheContainer,t,this.initCsvConfig());
//    }

    /**
     * 把传入的实例属性的值封装成字符串数组
     *
     * @param obj       实例
     * @return          字符串数组
     * @throws Exception    异常
     */
    private <T>  String[] coverFieldsValue(T obj,CsvConfig csvConfig) throws Exception {
        String[] result ;
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        if (null == fields || fields.length <= 0) {
            return null;
        }
        result = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            new Date();
            String methodName = "get" + fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1);
            Method method = clazz.getMethod(methodName);
            Object value = method.invoke(obj);
            if(null == value){
                continue;
            }
            if("Date".equals(fields[i].getType().getSimpleName())){
                Date date = (Date)value;
                result[i] = new SimpleDateFormat(csvConfig.getDateFormat()).format(date);
                continue;
            }
            result[i] = value.toString();
        }
        return result;
    }

    /**
     * 构造一个默认的配置实例
     * 默认编码格式为本地系统编码格式
     * @return      设有默认值的配置实例
     */
    private CsvConfig initCsvConfig(){
        String charset = System.getProperty("file.encoding");
        return new CsvConfig(charset,"yyyy-MM-dd HH:mm:ss:SSS",',');
    }

    /**
     * 检测给予系统配置信息的完整性
     * @param csvConfig        给定的配置实例
     */
    private void checkCsvConfig(CsvConfig csvConfig){
        if(null == csvConfig){
            csvConfig = initCsvConfig();
        }else{
            if(null == csvConfig.getCharset()){
                csvConfig.setCharset(System.getProperty("file.encoding"));
            }
            if(null == csvConfig.getDateFormat()){
                csvConfig.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            }
            //没有指定分隔符
            if(0 == csvConfig.getSeparator()){
                csvConfig.setSeparator(',');
            }
        }
    }
}

获取某行某列的数据

/**
     * 获取第几行,第几列的数据
     * @param row
     * @param col
     */
    static void test(int row, int col){
        try {
            BufferedReader reade = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null;
            int index=0;
            while((line=reade.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
                if(index==row-1){
                    System.out.println(item.length);
                    if(item.length>=col-1){
                        String last = item[col-1];//这就是你要的数据了
                        System.out.println(last);
                    }
                }
                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

获取某列的数据

private static void testCol(int col) {
        try {
            BufferedReader reade = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null;
            int index=0;
            reade.readLine(); //注释掉 第一行表头信息
            while((line=reade.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分

                    if(item.length>=col){
                        String last = item[col-1];//这就是你要的数据了
                        System.out.println(last);
                    }

                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值