【问题标题】:Leading zero in any column of a CSV file is lost when opened in Excel 2007在 Excel 2007 中打开 CSV 文件的任何列中的前导零都会丢失
【发布时间】: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/…

标签: java csv


【解决方案1】:

在另一个论坛上找到了这个解决方案,它对我有用。

附加双引号和制表符,问题将得到纠正。当数字中包含逗号(,)时,制表符可防止前导 zeor 截断和双引号分隔单元格。

String yourString = "002015";

解决方案:

"\"\t"+你的字符串 + "\"";

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 2016-11-25
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2017-01-15
    • 2015-08-25
    • 2013-06-05
    相关资源
    最近更新 更多