Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BadUncleX/aabb41a8cd2055f90ba07fd7c4556224 to your computer and use it in GitHub Desktop.
Save BadUncleX/aabb41a8cd2055f90ba07fd7c4556224 to your computer and use it in GitHub Desktop.
Shell script to add UTF-8 BOM to any file (from: https://gist.github.com/jamesqo/d65e10f6a2aa3fc6ffe0) 解决Excel乱码的问题

解决Excel乱码的问题

如下java代码导出的csv文件用Excel打开还是乱码, 用Sublime Text的Save with Encoding -> UTF-8 with BOM

public static void exportWithOpencsvBySql(String sql, String file) throws Exception {
        OutputStreamWriter ows = new OutputStreamWriter(new FileOutputStream(new File("/tmp/" + file)), "utf-8");
        try {
            CSVWriter writer = new CSVWriter(ows);
            System.out.println("file: " + file);
            Connection connection = getConnection();
            ResultSet myResultSet = getResultSet(connection, sql);
            writer.writeAll(myResultSet, true);
            writer.close();
            closeConnection(connection);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    
#!/bin/bash
## 用脚本比手工操作方便
file=$1
cat $file > $file".temp"
printf "\xEF\xBB\xBF" > $file
cat $file".temp" >> $file
rm $file".temp"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment