简体   繁体   中英

Need help in writing data to csv file in java

I am using the following code for appending data to a csv file using java:

fw.append("Company Name");
fw.append(',');
fw.append(',');
fw.append(',');
fw.append("Addres");
fw.append(',');
fw.append("Phones");
fw.append(',');
fw.append("Faxes");
fw.append(',');
fw.append("Websites");
fw.append(',');
fw.append('\n');
fw.append(companyName);
fw.append(',');
fw.append(address);
fw.append(',');
fw.append(phones);
fw.append(',');
fw.append(faxes);
fw.append(',');
fw.append(websites);
fw.append(',');
fw.append('\n');
fw.flush();

But I am not getting the result in the csv file in the proper format as required as per the code above specified.

Please help me in solving the problem.

Thanks in advance.

Regards

Instead of doing this, consider leveraging an open source solution that already addresses the generic CSV writing problem:

http://opencsv.sourceforge.net/

You should be using ; instead of , .

fw.append("Company Name");
              fw.append(','); // <-- extra
              fw.append(','); // <-- extra
              fw.append(',');
              fw.append("Addres");

This creates extra fields in your csv, and offsets your headers from their corresponding rows.

fw.append('\n');
              fw.append(companyName);  
              fw.append(',');   //  <-- only one comma, not three
              fw.append(address);
              fw.append(',');
              fw.append(phones);

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