Sunday 27 October 2013

Common problems facing while csv file writing in java


A few common problems we are facing while writing csv file in java. First of all csv file is a comma separated plain text file and can be opened with excel viewer. If a single word contains a comma, it can be considered as two words and will occupy two cells. Where as it should occupy only once cell.

Problem #1: When a value contains comma symbol, but still needs to be fitted into a single cell.
Solution: Enclose the string in double quotes.

Code:  
String string_variable = "Its heavy, but looks good";
new StringBuffer("\"").append(string_variable).append("\"").toString();

Problem #2: When a value contains numeric values starting with zeros, most of the programmers will suggest append single quote(') in front of the numeric number. But cell looks different when we add quote symbol.
Solution: 
String string_variable = "0009098765";
new StringBuffer("\t").append(string_variable).toString();

Note: When we are not aware coming value having either leading zero or commas, we can combine both solutions.

Code:
new StringBuffer("\"").append("\t").append(string_variable).append("\"").toString();

No comments:

Post a Comment