2

I want to write a csv file in Excel format (utf-8-bom) with the apache.commons.csv and the apache.commons.io. It have only a BOMInputStream method. It is a little paradox but i can't find any howto's for writing csv files in utf-8-bom for Excel.

Is it possible with java to write files with the BOM-coding? Have anybody a idea to make this? Thanks for help!

1
  • Just write the character BOM. Your encoder (when you are saving the file) will do the job. Commented Apr 23, 2018 at 15:31

2 Answers 2

1

This issue is delt with in this question. In general BOM is allowed but neither needed nor recommended in UTF-8. So all you need is to write a file in UTF-8. For details see the link to the question that deals with this issue

Sign up to request clarification or add additional context in comments.

1 Comment

In general yes, but opening a CSV in Excel needs the BOM to recognize UTF-8 content...
1

If you are adding header to CSV, simplest solution is to prefix first column header with BOM bytes:

public static final String UTF8_BOM = new String(new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF},StandardCharsets.UTF_8);
//...
String[] header = new String[2];
header[0] = UTF8_BOM + "column1";
header[1] = "column2";
final CSVFormat csvFormat = CSVFormat.EXCEL.withDelimiter(';').withHeader(header);
try(FileWriter fileWriter = new FileWriter(file);
        CSVPrinter csvPrinter = new CSVPrinter(fileWriter, csvFormat);){
    //write CSV data ...
}

This way you can use one 'try with resources' without caring when CSVPrinter prints header. Otherwise you have to make sure to write BOM before CSVPrinter writes header.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.