Apache Commons CSV解析器

时间:2018-08-08 10:43:36

标签: csv java-8 apache-commons

如何在不中继订单的情况下从CSV读取值?

即使内部使用.get("headerName")进行阅读,也取决于顺序。任何人都找到了更好的方法来解决此问题?

csv示例

header1,header2
1111111,2222222

3 个答案:

答案 0 :(得分:1)

最后,我编写了自己的逻辑以将csv映射到映射。虽然使用了具有基本功能的apache csv解析器。

 public List<Map<String, Object>> getMapFromCSV(MultipartFile multipartFile) {
        try {
            CSVParser parser = parseCSV(multipartFile.getInputStream());
            return getMap(parser.getRecords(), parser.getHeaderMap());
        } catch (IOException e) {
            throw new RunTimeException(e);
        }
    }

    private List<Map<String, Object>> getMap (List<CSVRecord> records, Map<String, Integer> headers) {
        Map<Integer, String> headerMap = formatHeaderMap(headers);
        List<Map<String, Object>> data = new ArrayList<>();
        for (int i = 1; i < records.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            try {
                CSVRecord record = records.get(i);
                for (int j = 0; j < record.size(); j++) {
                    map.put(headerMap.get(j), record.get(j));
                }
                data.add(map);
            } catch (Exception e) {
                throw new RunTimeException(e);
            }
        }
        return data;
    }

    private Map<Integer, String> formatHeaderMap(Map<String, Integer> map) {
        Map<Integer, String> data = new HashMap<>();
        map.forEach((k , v) -> {
            data.put(v, k);
        });
        return data;
    }

    private CSVParser parseCSV(InputStream inputStream) {
        try {
            return new CSVParser(new InputStreamReader(inputStream), CSVFormat.DEFAULT
                    .withFirstRecordAsHeader()
                    .withIgnoreHeaderCase()
                    .withSkipHeaderRecord()
                    .withTrim());
        } catch (IOException e) {
            throw new RunTimeException(e);
        }
    }

答案 1 :(得分:0)

您可以尝试使用univocity-parsers选择要获取的列。

CsvParserSettings settings = new CsvParserSettings();
settings.selectFields("e", "d", "b", "a");

CsvParser parser = new CsvParser(settings);

//all rows will have the values of your selected headers only, in the order you defined above.
List<Record> allRecords = parser.parseAllRecords(new File("/path/to/your.csv"));

希望这会有所帮助

披露:我是这个图书馆的作者。它是开源且免费的(Apache 2.0许可证)

答案 2 :(得分:0)

我正在努力解决此问题,并找到了解决方案!您需要指定不带任何参数的.withHeaders()调用,以允许库为列计算正确的索引。例如:

DoublyLinkedNode