0

I am printing some data into a CSV file using Apache Commns CSV. One of the fields contains 15 digit number and is of type String. This field prints as exponential number in CSV instead of a complete number. I know Excel does that but is there a way in java to print it as a complete number.

I am not doing anything special. Initially I thought that Commons CSV will take care of it.

public void createCSV(){
   inputStream = new FileInputStream("fileName");
   fileWriter = new FileWriter("fileName");
   csvFileFormat = CSVFormat.Excel.withHeader("header1", "header2");
   csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

   for(List<UiIntegrationDTO dto: myList>){
   String csvData = dto.getPolicyNumber();
   csvFilePrinter.PrintRecord(csvData);
   }
}
Jaykumar
  • 165
  • 1
  • 8
  • 23
  • We need to see what code you have written so far. I'm guessing you want to convert the number in question as `BigDecimal`, but we really need the code. – markspace Jul 23 '16 at 17:35
  • @markspace. I've updated my post. This is how I am doing it. Basically I invoke this method to my Struts2 action. So this is how I am getting the data from POJO and write it into CSV.I want the policy number to show up as a complete number like 123456789101112 not as exponent. – Jaykumar Jul 23 '16 at 17:52
  • `dto.getPolicyNumber()` returns a String, is not it? If so, then the conversion to exponential notation happens not in the code you gave, but somewhere inside `dto.getPolicyNumber()`. – Ruslan Batdalov Jul 23 '16 at 18:09
  • Yes this returns a String. But dto is just a Java Bean.There is no logic in it. – Jaykumar Jul 23 '16 at 18:12
  • OK, then how you assign a value to this field? – Ruslan Batdalov Jul 23 '16 at 18:21
  • I get it from the db.From the db it comes as a "123456789101112" but on the excel it shrinks to exponent. – Jaykumar Jul 23 '16 at 18:23
  • This field is a String so Excel should treat it as a text right, but somehow it is not. – Jaykumar Jul 23 '16 at 18:28
  • I have just tried a shortened version of your code, and it prints the whole string. You are talking about Excel. Do you mean that the value is shown in the exponential notation in Excel? Have you checked the actual CSV file content? – Ruslan Batdalov Jul 23 '16 at 18:39
  • Yes, I've checked the file. If you double click on the value then Excel changes it to a complete number but when the file is downloaded this field comes as a exponent. – Jaykumar Jul 23 '16 at 18:44

1 Answers1

1

Prepend apostrophe

As far as I understand from the discussion in comments, it is a question about Excel interpretation of CSV file, but the file itself contains all necessary data.

I think, csvFilePrinter.PrintRecord("'" + csvData); should help. Apostrophe requires Excel to interpret a field as a string, not as a number.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ruslan Batdalov
  • 793
  • 1
  • 8
  • 21