简体   繁体   中英

How to print commas to a .csv file using PrintWriter in Java?

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM