仅导入CSV文件中的特定列

时间:2018-03-14 13:24:17

标签: java csv opencsv

我正在尝试使用Java库openCSV导入CSV文件。有没有办法只加载特定列而不是全部列?我现在的代码是:

JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter(
                        "CSV file", "csv");
                fileopen.addChoosableFileFilter(filter);

                int ret = fileopen.showDialog(null, "Choose file");
                                if (ret == JFileChooser.APPROVE_OPTION) {
    try {
        File file = fileopen.getSelectedFile();
        System.out.println("Opening: " + file.getName());
        File csvFilename = fileopen.getSelectedFile();
        try (CSVReader csvReader = new CSVReader(new FileReader(csvFilename), ',', '\'',11 )) {
            String[] row = null;
            while((row = csvReader.readNext()) != null) {
                System.out.println(row[0]
                        + " # " + row[1]
                        + " #  " + row[2]);
            }
        } 
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Glass_search.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Glass_search.class.getName()).log(Level.SEVERE, null, ex);
    }

    }

这个文件也有标题所以也许这样吗?

2 个答案:

答案 0 :(得分:1)

如果使用CSVReaderBuilder创建CSVReader实例,则可以设置自己的解析器供读者使用。您只需要创建自己的解析器来实现ICSVParser接口。

答案 1 :(得分:1)

对于特定情况,univocity-parsers更适合您,因为您可以轻松选择要获取的列:

CsvParserSettings parserSettings = new CsvParserSettings();
settings.detectFormatAutomatically(); //detects the format 

//extracts the headers from the input
settings.setHeaderExtractionEnabled(true);

//or give the header names yourself
// if you use this it will override the headers read from the input (enabled above).
settings.setHeaders("A", "B", "C");

//now for the column selection
settings.selectFields("A", "C"); //rows will contain only values of column "A" and "C"
//or
settings.selectIndexes(0, 2); //rows will contain only values of columns at position 0 and 2

List<String[]> rows = new CsvParser(settings).parseAll(new File("/path/to/your.csv"), "UTF-8");

您还可以在List

中获取每列的值
ColumnProcessor columnProcessor = new ColumnProcessor();
settings.setProcessor(columnProcessor);
CsvParser parser = new CsvParser(settings);
parser.parse(new File("/path/to/your.csv), "UTF-8"); //all rows are submitted to the processor created above.

Map<String, List<String>> columnValues = columnProcessor.getColumnValuesAsMapOfNames();

这应该解决你所有的问题,希望它有所帮助。

免责声明:我是这个图书馆的作者。它是开源和免费的(Apache 2.0许可证)