简体   繁体   English

在Excel中打开时使用SuperCsv写入文件以保留前导零

[英]Write file with SuperCsv preserving leading zeros while opening in excel

I was wondering if there is a way to keep the leading 0 while using SuperCsv. 我想知道在使用SuperCsv时是否有办法保持前0。

My problem is that I have a few columns which have numbers with leading 0. I want to keep the 0, but excel keeps stripping it, I've also tried to append a few characters at the beginning of the number like ' = " but no good result. 我的问题是我有一些列的数字以0开头。我想保留0,但是excel一直在剥离它,我还尝试在数字的开头添加一些字符,例如'=“,但是没有好结果。

Excel is displaying the first character which I've added at the beginning of the number, so the column value looks like =0222333111 , and that's because probably supercsv is wrapping the output between quotes. Excel将显示我在数字开头添加的第一个字符,因此列值看起来像== 0222333111,这是因为supercsv可能会将输出包装在引号之间。

I didn't find anything on the superCsv website and I guess I am not the only one who has this problem. 我在superCsv网站上没有找到任何东西,我想我不是唯一遇到此问题的人。 Should I migrate the to an Excel Java lib, or there is a workaround? 我应该将其迁移到Excel Java库还是有解决方法?

The CSV file format does not allow you to specify how the cells are treated by external programs. CSV文件格式不允许您指定外部程序如何处理单元格。 Even if the leading zeroes are written to the CSV file (please check that, if you have not already done so), Excel might think that it's smarter than you, that the leading zeroes are there by accident and discard them. 即使将前导零写入到CSV文件中(请检查并确认,如果您尚未这样做),Excel可能会认为它比您更聪明,偶然出现前导零并丢弃它们。

Even if there where some workarounds like adding all sorts of invisible Unicode characters, this is just a hack that is not guaranteed to work with other versions of Excel. 即使存在一些变通办法,例如添加各种不可见的Unicode字符,这也不能保证与其他版本的Excel一起使用。

Therefore, CSV seems not to be an adequate file format for your requirements. 因此,CSV似乎不是满足您要求的适当文件格式。 Either switch to a different file format, or configure Excel to treat all cells as strings instead of numbers (I don't know how or if the latter is possible). 要么切换到其他文件格式,要么将Excel配置为将所有单元格都视为字符串而不是数字(我不知道如何或是否可以使用数字)。

In supercsv, you can use custom cellprocessor below, it will append = in your cell value 在supercsv中,您可以在下面使用自定义单元处理器,它将在您的单元格值中附加=

public class PreserveLeadingZeroes extends CellProcessorAdaptor {

    private static final Logger LOG = LoggerFactory.getLogger(PreserveLeadingZeroes.class);

    public PreserveLeadingZeroes() {
        super();
    }

    public PreserveLeadingZeroes(CellProcessor next) {
        super(next);
    }

    public Object execute(Object value, CsvContext context) {

        if (value == null) {
            // LOG.debug("null customer code");
            final String result = "";
            return next.execute(result, context);
        }
        // LOG.debug("parse customer code : " + value.toString());
        final String result = "=\"" + value.toString() + "\"";
        return next.execute(result, context);
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM