Reputation: 2274
I have gone through other questions regarding this on StackOverflow but libraries mentioned there only allow to read or write. Some of them do allow partial read or write like SuperCSV but no library can be used for updating value of a particular cell. Is there some other library that can be used or do I need to do it manually?
Upvotes: 0
Views: 3019
Reputation: 1
There is no in build function to edit csv file. Here is one approach to edit csv file.
package maven.selenium;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import jxl.read.biff.BiffException;
import jxl.read.biff.File;
public class App {
public static void main(String[] args) throws BiffException, IOException {
String csv = "C:/Users/shubham.mahajan/Desktop/data.csv";
CSVReader reader = new CSVReader(new FileReader(csv), ',');
List<String[]> csvBody = reader.readAll();
String[] First_Row = csvBody.get(0);
CSVWriter writer = new CSVWriter(new FileWriter(csv), ',');
writer.writeNext(First_Row);
for (int k = 0; k < First_Row.length; k++) {
if (First_Row[k].equals("value")) {
for (int j = 1; j < csvBody.size(); j++) {
String[] Temp = csvBody.get(j);
Temp[k] = "replacing value";
writer.writeNext(Temp);
}
}
}
reader.close();
writer.flush();
writer.close();
}
}
Upvotes: 0
Reputation: 7899
No, there is no way to directly update the cell in CSV file. You can read CSV line by line and then column by column , update the cell (content) and write to a new file.
And if you know the pattern(regex) then you can use String.replace() method.
Upvotes: 1
Reputation: 36446
Read in the CSV, modify the cell you want, then write it back to the file.
Upvotes: 1