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....
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!
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();
}
You're doing something like this:
String line = readLineFromFile();
line.replace(...);
This is not editing the file, it's creating a new string from a line in the file.
String instances are immutable, so the replace call you're making returns a new string it does not modify the original string.
Either use a file stream that allows you to both read and write to the file - i.e. RandomAccessFile or (more simply) write to a new file then replace the old file with the new one
In psuedo code:
for (String line : inputFile) {
String [] processedLine = processLine(line);
outputFile.writeLine(join(processedLine, ","));
}
private String[] processLine(String line) {
String [] cells = line.split(","); // note this is not sufficient for correct csv parsing.
for (int i = 0; i < cells.length; i++) {
if (wantToEditCell(cells[i])) {
cells[i] = "new cell value";
}
}
return cells;
}
Also, please take a look at this question. There are libraries to help you deal with csv.
CSV file is just a file. It is not being changed if you are reading it.
So, write your changes!
You have 3 ways.
1
read line by line finding the cell you want to change.
change the cell if needed and composite new version of current line.
write the line into second file.
when you finished you have the source file and the result file. Now if you want you can remove the source file and rename the result file to source.
2
Use RandomAccess file to write into specific place of the file.
3
Use one of available implementations of CSV parser (e.g. http://commons.apache.org/sandbox/csv/)
It already supports what you need and exposes high level API.
Related
I am new to Java. I was successfully able to read my CSV file from my local file location and was able to identify which column needed to be deleted for my requirements. However, I was not able to delete the required column and write the file into my local folder. Is there a way to resolve this issue? I have used the following code:
CSVReader reader = new CSVReader(new FileReader(fileName));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
System.out.println(nextLine[15]);
}
All I would like to do is to remove the column having index 15 and write the file as a CSV file in my local folder.
I'm assuming you're using the OpenCSV library.
In order to make your code work, you have to fix 2 issues:
You need a writer to write your modified CSV to. OpenCSV provides a CSVWriter class for this purpose.
You need to convert your line (which is currently a String array) into a list to be able to remove an element, then convert it back into an array to match what the CSVWriter.writeNext method expects.
Here's some code that does this:
CSVReader reader = new CSVReader(new FileReader(fileName));
CSVWriter writer = new CSVWriter(new FileWriter(outFileName));
String[] origLine;
while ((origLine = reader.readNext()) != null) {
List<String> lineList = new ArrayList<>(Arrays.asList(origLine));
lineList.remove(15);
String[] newLine = lineList.toArray(new String[lineList.size()]);
writer.writeNext(newLine, true);
}
writer.close();
reader.close();
Some additional remarks:
The code probably needs a bit more error handling etc if it's to be used in a production capacity.
List indices in Java start at 0, so remove[15] actually removes the 16th column from the file.
The code writes its output to a separate file. Trying to use the same file name for input and output will not work.
I have an issue when trying to edit specific data into csv file.
input csv(inputfile.csv) :
username,password,status
uname1,pwd1,todo
uname2,pwd2,todo
uname3,pwd2,pass
required output in same csv(inputfile.csv) :
username,password,status
uname1,pwd1,pass
uname2,pwd2,pass
uname3,pwd2,pass
I tried to do this using apache poi for csv operation as well as OpenCSV. but I cold append the new result like :
username,password,status
uname1,pwd1,todo
uname2,pwd2,todo
uname3,pwd2,pass
uname1,pwd1,pass
Unable to replace the existing record. can someone please suggest any help?
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();
}
CSVWriter writer = new CSVWriter(new FileWriter("C:\\Downloads\\spred.csv",
true));
String [] record = "user7,pwd10,pass".split(",");
writer.writeNext(record);
System.out.println("Write succesfully");
writer.close();
I am looking for a way to export a JTable with data to a .csv file. But I didn't find a good method to do that. It works and generates the csv file. But There is a problem. When there is data in a jTable column like this,
|column 1|column 2|
-------------------
|Java, C#|PHP |
The result is,
column 1,column2,
Java,C#,PHP,
So the problem id there are only 2 columns and 2 data columns but for CSV file, there are 3 data columns. When importing that CSV file to the Excel sheet it is completely wrong. Data went to different locations.
So is there another way to do this in Java or any way to avoid this problem?
Thanks for the help in advance! Best Regards.
I use the following code.
public void ExportToCSVfile(JTable table) throws IOException, ClassNotFoundException
{
Writer writer = null;
DefaultTableModel defaultTableModel = (DefaultTableModel) table.getModel();
int Row = defaultTableModel.getRowCount();
int Col = defaultTableModel.getColumnCount();
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.csv"), "utf-8"));
StringBuffer bufferHeader = new StringBuffer();
for (int j = 0; j < Col; j++) {
bufferHeader.append(defaultTableModel.getColumnName(j));
if (j!=Col) bufferHeader.append(", ");
}
writer.write(bufferHeader.toString() + "\r\n");
for (int i = 0 ; i < Row ; i++){
StringBuffer buffer = new StringBuffer();
for (int j = 0 ; j < Col ; j++){
buffer.append(defaultTableModel.getValueAt(i,j));
if (j!=Col) buffer.append(", ");
}
writer.write(buffer.toString() + "\r\n");
}
} finally {
writer.close();
}
}
So is there another way to do this in Java or any way to avoid this problem?
I don't know all the rules of a CSV formatted file but I believe for something this simple where a cell contains a "," you can just delimit the entire text of the cell.
So the ouput of your file should be:
column 1,column2,
"Java,C#",PHP,
This is easy to verify you just create a simple spreadsheet where the cell contains a comma and then you export the spreadsheet to a .csv file and check the format of the file in a text editor.
I think you can delimit all data with "..." even if it doesn't contain a comma but you will need to verify that.
So you need to modify your export code to include the delimiters.
I am using the accepted answer from here. Basically, I am converting a csv to .xlsx, and it looks like the solution pulls everything in individual cells into 1 line using the buffered reader, and then using:
String str[] = currentLine.split(",");
.. the string is split up into separate parts of the array for each column. My problem is that in some of my data, there are commas, so the algorithm gets confused and makes more columns than needed, splitting sentences into different columns which doesn't really work for me. Is there another way I can split the sentences up perhaps? I'd happily split the string up using a different unique character (maybe |?), but I don't know how to replace the comma provided by the bufferedreader. Any help would be great. Code I am using below for reference:
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}
Well, CSV is something more than just text file with lines separated with commas.
For example, some fields in CSV can be quoted; this is the way comma is escaped within one field.
Quotes are quoted as well, with double-quotes.
And there also could be newlines within one CSV line, they must also be quoted.
So, to sum up, a CSV lines
1,"2,3","4
5",6,7,""""
should be parsed to array of "1", "2,3", "4\n5", "6", "7","\"" (and that is a single row of a CSV table).
As you can see, you can't just mindlessly split every line by comma. I suggest you to use some library instead of doing this by yourself. http://www.liquibase.org/javadoc/liquibase/util/csv/opencsv/CSVReader.html will work just fine.
I am reading a CSV file and using OpenCSV to read it and CircularFifoBuffer to split the data into columns and assign the value from each column to a string. This works fine for reading a specific row in the csv file, however I wish to read the csv file line by line starting at the beginning and working downwards to the final row.
Then each time a row is read the string values will be compared and provided a given condition is satisfied the next row will be read.
I can handle all of the above bar processing the CSV data line by line.
Any pointers would be greatly appreciated.
Directly from the FAQ:
If you want to use an Iterator style pattern, you might do something like this:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
Or, if you might just want to slurp the whole lot into a List, just call readAll()...
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
which will give you a List of String[] that you can iterate over. If all else fails, check out the Javadoc.