【发布时间】:2011-09-15 21:30:02
【问题描述】:
我正在寻找一种在导出到 Java 中的 CSV 文件时保留整数中前导零的方法。以下是在 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.");
}
}
当我在 Excel 2007 中打开输出文件时,我丢失了前导零。有没有办法保留这些零并在 Excel 中打开它们而不转换为字符串?不将它们转换为字符串的原因是因为'我需要将整数运算应用于 excel 中的这些值。
想法?
【问题讨论】:
-
带前导零的数字是字符串。
-
正如@ceeyayoz 所说,一个数字没有前导零,所以没有什么可以保留的。如果它有前导零,它是一个字符串,整数运算不适用。您需要确定它们是整数(因此没有前导零,可以用作整数)还是字符串,可以有任何前导。
-
您可以使用 Excel 中整数的自定义格式来完成此操作:support.microsoft.com/en-us/help/81518/…