2

I am creating a csv file that contains data but when opening it with Excel MS all leading zeros are being stripped. What should I write in the csv file to prevent that from occuring?

part of my code

for (int i=0; i < rows.size(); i++) {
    Object[] row = (Object[]) rows.get(i);
    bufferedWriter.write(row[0]);   
    bufferedWriter.write(";" + row[1]); 
    bufferedWriter.write(";" + row[2]); 
    bufferedWriter.write(";" + row[3]); 
    bufferedWriter.write(";" + row[4]);     
            if(row[4].startsWith("0")){
               //I want to add something here tp prevent that to happen.
            }
    bufferedWriter.write(";" + row[5]); 
    bufferedWriter.write(";" + row[6]);
    try { bufferedWriter.write(";" + DF.format(row[7])); }  
    catch (Exception ex) { bufferedWriter.write(";0"); }
    try { bufferedWriter.write(";" + DF.format(Double.parseDouble(row[8]))); }  
    catch (Exception ex) { bufferedWriter.write(";0"); }
    String text = (row[9] != null) ? row[9].replace(';', ',') : "";
    bufferedWriter.write(";" + text); 
    bufferedWriter.writeLine(";" + row[10]); 
}
TheBook
  • 1,698
  • 1
  • 16
  • 32

3 Answers3

1

This should preserve the leading zeros:

value1;="001234";value3

Note that without the =, the field will be handled just as a quoted field (not as a string) that could contain a seperator.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
0

This isn't a full answer, but I don't think that this is necessarily a Java problem, at least not entirely. Assuming you write string data to your CSV file which contains the leading zeroes you want, then when you import this data to Excel all this information should still be there.

Read this SO post for a number of methods for how to preserve leading zeroes when importing CSV. You may be able to do something as simple as formatting the column in question as fixed width text.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

So it works for me if I add it in this way.

"\"\t"+ row[4] + "\"\t";
TheBook
  • 1,698
  • 1
  • 16
  • 32