I'm looking for a way to preserve leading zeros in integers when exporting to a CSV file in Java. The following is an example of generating leading zeros into a CSV.
开发者_如何学编程public class TestLargeDataset {
int one_million = 1000000;
public void writeMillionRowsToCSVFile(String fqname) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(fqname)));
byte[] newLine = "\n".getBytes();
for(int x = 0; x < one_million; x++) {
bos.write(("0" + x + ",").getBytes());
bos.write(("0" + (x+1) + ",").getBytes());
bos.write(("0" + (x+2) + ",").getBytes());
bos.write(("0" + (x+3)).getBytes());
bos.write(newLine);
}
bos.close();
}
/*
* Main.
*/
public static void main(String a[]) throws Exception {
TestLargeDataset tlr = new TestLargeDataset();
long startTime2 = System.nanoTime();
tlr.writeMillionRowsToCSVFile("C:\\output_" + System.currentTimeMillis() + ".csv");
long diff2 = (System.nanoTime() - startTime2)/1000000000;
tlr.log("Executed file write operation in " + diff2 + " seconds (~" + (diff2/60) + " minutes)");
tlr.getStatement().close();
tlr.getConnection().close();
tlr.log("Execution complete.");
}
}
When I open the output file in Excel 2007, I lose the leading zeros. Is there a way to preserve these zeros and open the same in Excel WITHOUT converting then into Strings? The reason for not converting them into Strings is cos' I would need integer arithmetic applied to these values in the excel.
Thoughts?
Found this solution on another forum and it worked for me.
Append a double quote and tab, problem will rectify. Tab prevent leading zeors from truncating and double quote separation of a cell when numbers has comma(,) with in it.
String yourString = "002015";
Solution:
"\"\t"+yourString + "\"";
精彩评论