使用java更新特定的单元格csv文件

Jav*_*irl 4 java csv

嗨,我有一个小问题,我想我只是没有在一行代码中获得正确的语法。基本上,我可以写入我的 csv 文件并使用字符串标记器查找特定记录,但它不会更新/编辑该记录的指定单元格。记录保持不变。请帮忙....

小智 6

我在 java 中使用过http://opencsv.sourceforge.net

嗨,这是通过指定行和列来更新 CSV 的代码

/**
 * Update CSV by row and column
 * 
 * @param fileToUpdate CSV file path to update e.g. D:\\chetan\\test.csv
 * @param replace Replacement for your cell value
 * @param row Row for which need to update 
 * @param col Column for which you need to update
 * @throws IOException
 */
public static void updateCSV(String fileToUpdate, String replace,
    int row, int col) throws IOException {

File inputFile = new File(fileToUpdate);

// Read existing file 
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column  and replace with by using row and column
csvBody.get(row)[col] = replace;
reader.close();

// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
Run Code Online (Sandbox Code Playgroud)

这个解决方案对我有用,干杯!


man*_*ear 5

我使用下面的代码,将一个字符串替换为另一个字符串,它的工作方式完全符合我需要的方式:

public static void updateCSV(String fileToUpdate) throws IOException {
        File inputFile = new File(fileToUpdate);

        // Read existing file
        CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
        List<String[]> csvBody = reader.readAll();
        // get CSV row column and replace with by using row and column
        for(int i=0; i<csvBody.size(); i++){
            String[] strArray = csvBody.get(i);
            for(int j=0; j<strArray.length; j++){
                if(strArray[j].equalsIgnoreCase("Update_date")){ //String to be replaced
                    csvBody.get(i)[j] = "Updated_date"; //Target replacement
                }
            }
        }
        reader.close();

        // Write to CSV file which is open
        CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
        writer.writeAll(csvBody);
        writer.flush();
        writer.close();
    }
Run Code Online (Sandbox Code Playgroud)


Ale*_*exR -1

CSV 文件只是一个文件。如果您正在阅读它,它不会被更改。因此,写下您的更改!

你有3种方法。

1

  1. 逐行阅读找到您要更改的单元格。
  2. 如果需要,更改单元格并合成当前行的新版本。
  3. 将该行写入第二个文件。
  4. 完成后,您将获得源文件和结果文件。现在,如果您愿意,可以删除源文件并将结果文件重命名为 source.txt。

2

使用 RandomAccess 文件写入文件的特定位置。

3

使用 CSV 解析器的可用实现之一(例如http://commons.apache.org/sandbox/csv/)它已经支持您需要的内容并公开高级 API。