仅从一个CSV文件中提取某些列以写入另一个CSV文件

时间:2015-10-06 09:36:26

标签: java csv

我正在从一个 CSV.1 文件写入另一个 CSV.2 文件。但我只想提取某些列而不是从 CSV.1 文件到 CSV.2 文件的所有内容。有没有办法做到这一点?顺便说一句,我使用Java来做到这一点。感谢。

2 个答案:

答案 0 :(得分:1)

我建议使用像OpenCSV这样的库。 Pleasae看一下这方面的文档。

但如果您想使用自己的代码",您可以使用以下内容:

// Set your splitter, mostly "," or ";"
String csvSplitter = ";" 
// A buffered reader on the input file
BufferedReader br = new BufferedReader(new FileReader("CSV.1"));
// A writer to the output file
PrintWriter output = new PrintWriter("CSV.2", "UTF-8");
// Read line after line until EOF
while ((line = br.readLine()) != null) {
    // Split the current line into columns
    String[] cols = line.split(csvSplitter);
    // Only write the needed columns to the output file (eg. columns at index 4, 5 and 8)
    output.println(cols[4] + csvSplitter + cols[5] + csvSplitter + cols[8]);

}

答案 1 :(得分:0)

您可以在Java中执行此操作,因为当您使用Java读取CSV文件时,您会逐行阅读。 因此,对于每一行,您使用CSV分隔符拆分行。您将为此行提供逐列的内容数组。然后你跳过你不想要的专栏。 你为每一行重复一遍。

相关问题