0

I was wondering if there is a way to keep the leading 0 while using SuperCsv.

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.

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.

I didn't find anything on the superCsv website and I guess I am not the only one who has this problem. Should I migrate the to an Excel Java lib, or there is a workaround?

tshepang
  • 12,111
  • 21
  • 91
  • 136

2 Answers2

0

The CSV file format does not allow you to specify how the cells are treated by external programs. 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.

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.

Therefore, CSV seems not to be an adequate file format for your requirements. 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).

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

In supercsv, you can use custom cellprocessor below, it will append = in your cell value

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);
    }
} 
fearaus
  • 21
  • 5