我正在寻找一种在 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.");
}
}
Run Code Online (Sandbox Code Playgroud)
当我在 Excel 2007 中打开输出文件时,我丢失了前导零。有没有办法保留这些零并在 Excel 中打开它们,而不将其转换为字符串?不将它们转换为字符串的原因是因为我需要对 Excel 中的这些值应用整数算术。
想法?
小智 6
在另一个论坛上找到了这个解决方案,它对我有用。
附加双引号和制表符,问题将得到纠正。当数字中包含逗号 (,) 时,制表符可防止前导 zeors 截断和双引号分隔单元格。
字符串yourString =“002015”;
解决方案:
"\"\t"+yourString + "\"";
| 归档时间: |
|
| 查看次数: |
9609 次 |
| 最近记录: |