简体   繁体   中英

how to write to csv with a leading zero?

I wish to write to a CSV file some data. One of the column that I input the information is in the form of an integer with leading zeros, example: 0000000013.

For some reason, excel 'converts' it to 13, and I must have it with 10 digits (0000000013). Can anyone tell how this can be circumvented?

String value = "0000000013"; //I tried String.format("%8d", 13) doesn't work
printWriter.println(value);

Thanks!!!

Append tab to the number

ex: "\t"+"01234"

Add a single quote, ' , at the start of the line. This informs Excel to not treat the value as a number.

Even better way is to print your number as ="0000000013"

String value = "0000000013"; 
printWriter.println("=\"" + value + "\"");

When one opens a CSV file in excel 2007, it opens the Text Import Wizard. In step 3, you can specify the column data format of the column to be 'Text'. Just select the appropriate column header in the 'Data preview' pane. Then select the 'Text' radio button in the 'Column data format' pane.

The issue is that excel treats the cell as general format so it truncates all zeros, if you can't change cell type to Text, then use mentioned previously:

    printWriter.write("=\"" + value + "\"");

or

    printWriter.println("=\"" + value + "\"");
     
    

Please note that you cant simply use

    write("\"" + value + "\"")

You should append = symbol, ie assign the value.

But using:

    println("'" + value + "'") or println("'" + value)

Will also display single quotes in excel file, if this is fine with you can also use that.

Try:

String.format("%08d", 13)

Note the 0 in the format string, that tells Java to prefix the number with zeroes up to the length indicated in the field (8 in this case).

你应该使用:

String.format("%08d", 13);

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