Java通过javacsv实现读取csv文件数据

目录

1、添加依赖

2、测试的csv文件

3、实际调用代码

 4、返回的数据格式


1、添加依赖

<!--csv文件操作-->
<dependency>
	<groupId>net.sourceforge.javacsv</groupId>
	<artifactId>javacsv</artifactId>
	<version>2.0</version>
</dependency>

2、测试的csv文件

3、实际调用代码

package com.shucha.deveiface.biz.test;

import com.csvreader.CsvReader;
import com.monitorjbl.xlsx.StreamingReader;
import com.sdy.common.model.BizException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.All;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tqf
 * @Description
 * @Version 1.0
 * @since 2022-05-07 11:29
 */
public class test2022 {
    public static void main(String[] args) throws BizException, IOException {
        File csvFile = new File("D:\\123\\测试csv.csv");
        readCsvByCsvReader(csvFile);
        readCsvByBufferedReader(csvFile.getPath());

    }

    public static Map<String, Object> readCsvByCsvReader(File file) {
        Map<String, Object> mapData = new HashMap<>();
        String fileName = file.getName();
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
        mapData.put("sheetName",fileName);

        ArrayList<String> strList = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            ArrayList<String[]> arrList = new ArrayList<String[]>();
            // 如果生产文件乱码,windows下用gbk,linux用UTF-8
            CsvReader reader = new CsvReader(file.getPath(), ',', Charset.forName("UTF-8"));
           // 读取表头
            reader.readHeaders();
            String[] headArray = reader.getHeaders();//获取标题
            // System.out.println(headArray);
            while (reader.readRecord()) {
                // System.out.println(Arrays.asList(reader.getValues()));
                // 按行读取,并把每一行的数据添加到list集合
                arrList.add(reader.getValues());
            }
            reader.close();
            // System.out.println("读取的行数:" + arrList.size());
            // 如果要返回 String[] 类型的 list 集合,则直接返回 arrList
            // 以下步骤是把 String[] 类型的 list 集合转化为 String 类型的 list 集合
            for (int i = 1; i < arrList.size(); i++) {
                // 组装String字符串
                // 如果不知道有多少列,则可再加一个循环
                Map<String, Object> map = new HashMap<>();
                for (int j=0;j<arrList.get(0).length;j++) {
                    map.put(""+arrList.get(0)[j]+"", arrList.get(i)[j]);
                }
                // 返回的数格为拼接
                /*String ele = arrList.get(i)[0] + "," + arrList.get(i)[1] + "," + arrList.get(i)[2];
                System.out.println(ele);
                strList.add(ele);*/
                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapData.put("data",list);
        return mapData;
    }

    /**
     * BufferedReader 读取
     * @param filePath
     * @return
     */
    public static ArrayList<String> readCsvByBufferedReader(String filePath) {
        File csv = new File(filePath);
        csv.setReadable(true);
        csv.setWritable(true);
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(new FileInputStream(csv), "UTF-8");
            br = new BufferedReader(isr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String line = "";
        ArrayList<String> records = new ArrayList<>();
        try {
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                records.add(line);
            }
            System.out.println("csv表格读取行数:" + records.size());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(records);
        return records;
    }
}

 4、返回的数据格式

第一个方法返回数据:

{sheetName=测试csv, data=[{name=第1条数据, id=1, type=语文}, {name=第2条数据, id=2, type=数学}, {name=第3条数据, id=3, type=英语}, {name=第4条数据, id=4, type=美术}, {name=第5条数据, id=5, type=体育}, {name=第6条数据, id=6, type=}]}

第二个方法返回数据:

["id","name","type", "1","第1条数据","语文", "2","第2条数据","数学", "3","第3条数据","英语", "4","第4条数据","美术", "5","第5条数据","体育", "6","第6条数据",]

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码奴生来只知道前进~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值