我正在使用javacode将数据写入A.csv文件,然后读取A.csv文件并写入数据库。我有中文数据,但 Excel 无法正确识别,得到垃圾值。有什么方法可以告诉excel以utf8打开csv文件,以便javacode读取utf8字符并将其写入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")));
}
}
默认情况下,Excel 会尝试使用用户的区域设置来确定打开 CSV 时使用哪个 8 位 Windows 字符集。
通过在文件顶部添加 UTF-8 BOM,Excel(Windows 和 Mac >2013)将以 UTF-8 模式打开文件。
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();
}
当 Microsoft Excel 以 CSV UTF-8 保存文件时,它会在文件开头添加三个字节。这是一个实现此目的的 java 静态方法:
public static void makeFileExcelUTF8(String filename) {
try {
Path path = Paths.get(filename);
byte[] fileBytes = Files.readAllBytes(path);
if (fileBytes[0] == (byte) 239 && fileBytes[1] == (byte) 187 && fileBytes[2] == (byte) 191) {
System.out.println(filename + " is already in excel utf8 format");
return;
}
byte[] prefixBytes = new byte[3];
prefixBytes[0] = (byte) 239;
prefixBytes[1] = (byte) 187;
prefixBytes[2] = (byte) 191;
Files.write(path, prefixBytes);
Files.write(path, fileBytes, StandardOpenOption.APPEND);
}
catch (Exception e) {
System.out.println("problem saving into excel utf8 format");
}
}
您使用的编码不支持中文字母,但是将 UTF-8 更改为 UTF-16,这将适合您的解决方案,因为它支持中文字母。
如果您希望在将来的更新中支持表情符号等,请使用UTF-32。
希望这能最好地解决您的问题。