简体   繁体   中英

CSV file genereated using java when opened in excel sheet formats date for only few cells

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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