gpt4 book ai didi

java - 仅从 CSV 文件导入特定列

转载 作者:行者123 更新时间:2023-11-30 02:13:44 25 4
gpt4 key购买 nike

我正在尝试使用 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);
}

}

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

最佳答案

对于该特殊情况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 许可证)

关于java - 仅从 CSV 文件导入特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49278953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com