简体   繁体   中英

Is there any way through java program i can tell the Excel to open csv file in utf8?

I am writing data to A.csv file using javacode and then reading A.csv file and writing into DB. I have data in Chinese language and excel is not recognising properly, getting junk values. Is there any way i can tell excel to open the csv file in utf8, so that javacode reads utf8 characters and write it into Db ?

public class T {

CSVWriter out = null;

private void write(String[] values) throws IOException {
    out.writeNext(values);
}

public static void main(String[] args) throws IOException {

    File f  = new File("s.csv");

    FileOutputStream os = new FileOutputStream(f, false);

    CSVWriter out = new CSVWriter(
        new BufferedWriter(
            new OutputStreamWriter(
                os, "UTF-8")));
}
}

By default Excel tries to use the user's locale to determine which 8-bit Windows Charset to use when opening a CSV.

By adding a UTF-8 BOM to the top of the file, Excel (Windows and Mac >2013) will open the file in UTF-8 mode.

public static void main(String[] args) throws IOException {

    File f  = new File("s.csv");

    FileOutputStream os = new FileOutputStream(f, false);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                                            os, "UTF-8"));
    bw.write('\ufeff');

    CSVWriter out = new CSVWriter(bw);

    //English, Euro sign, German, Greek
    String[] row = {"hello there","€", "Würzburg", "Αριστοτέλης Τέλλυ Σαβάλας"};

    out.writeNext(row);

    out.close();
}

The encoding that you're using does not support Chinese letters, however change the UTF-8 to UTF-16, which will suit your solution as it supports Chinese letters.

If you wish to support emojis etc. in future updates, use UTF-32.

Hope that this solves your problem, best.

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