0

I have written following code:

CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withEscape('\\');
FileWriter fileWriter = new FileWriter(csvFile);
CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter,csvFileFormat);

function printCSV(String fieldValue,String dataType,CSVPrinter csvFilePrinter){
    if(dataType!=null && "date".equals(dataType)){
                    fieldValue = this.dateFormatter.format(new SimpleDateFormat("yyyy-MM-dd").parse(fieldValue));
    }
    csvFilePrinter.printRecord(fieldValue);
}

When the csv file is opened in excel sheet, only few cells are date formatted. I do not want date formatted and want to treat all cells as String. How can I do this?

DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
Radhika Kulkarni
  • 298
  • 1
  • 4
  • 19

1 Answers1

0

The if block from printCSV(..) method formats the date. You could remove it:

function printCSV(String fieldValue, String dataType, CSVPrinter csvFilePrinter)
{
    csvFilePrinter.printRecord(fieldValue);
}

And, as you can see, you can remove the printCSV(..) method and use directly csvFilePrinter.printRecord(fieldValue);

If you want Excel to treat all cells as string, and not auto formatting date so you have your own formatting "yyyy-MM-dd", you should take a look at this

Jorj
  • 1,291
  • 1
  • 11
  • 32
  • If block is necessary because i want to convet the date into specific format. Later on,I am converting it back to string – Radhika Kulkarni Mar 21 '18 at 15:35
  • You say "I do not want date formatted and want to treat all cells as String", that means you want excel to treat all cells as strings? Then why java tag? You should look at this https://stackoverflow.com/questions/165042/stop-excel-from-automatically-converting-certain-text-values-to-dates – Jorj Mar 21 '18 at 15:42