Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating specific cell csv file using java

Tags:

java

csv

Hi i have a small problem and think i'm just not getting the correct syntax on one line of code. basically, i can write into my csv file and find a specific record using string tokenizer but it is not updating/editing the specified cells of that record. the record remains the same. please help....

like image 976
JavaBabyGirl Avatar asked Dec 09 '10 11:12

JavaBabyGirl


People also ask

What is CSVReader in Java?

CSVReader – This class provides the operations to read the CSV file as a list of String array. CSVWriter – This class allows us to write the data to a CSV file. CsvToBean – This class will be used when you want to populate your java beans from a CSV file content.


2 Answers

I have used http://opencsv.sourceforge.net in java

Hi, This is the code to update CSV by specifying row and column

/**
 * 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();
}

This solution worked for me, Cheers!

like image 176
Chetan Aher Avatar answered Sep 22 '22 20:09

Chetan Aher


I used the below code where I will replace a string with another and it worked exactly the way I needed:

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();
    }
like image 33
mannedear Avatar answered Sep 21 '22 20:09

mannedear