Question

I have problems printing text to a .csv file. My String has a comma in it, and i end up printing it to TWO cell instead of ONE. Here is the code:

String companyName1 = "Edison Corporation, LLC co";
String profit1 = "$100";
String fileName = "Result.csv";
    File file = new File(fileName);
    output = new PrintWriter(file);
output.println(companyName+","+profit);
  //This gives me the following: 
  //  Edison Corporation             LLC co            $100
  //I need:
  //  Edison Corporation, LLC co     $100
Was it helpful?

Solution

CSV format allows strings with commas, but they must be enclosed in double quotes. Try this:

output.println("\""+companyName+"\","+profit);

OTHER TIPS

If you open the generated csv file in Excel, you'll have to consider that the default token separator and the escape char differs from the Locale settings of your office installation. German default in Excel is for example the semicolon and not the comma.

To be sure, open the csv in an Editor like NotePad++. In Excel use the "Import data..." functionality. There you can set the characters as you have defined in your code.

You can also have following CSV file:

7test7+7foo7+7ba77r7 

Where + is the token separator and 7 is the escape char.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top