我正在使用Apache POI读取 .docx
文件,并在执行一些操作后写入 .csv
。
我使用的 .docx
文件是法语,但是当我在 .csv
中写入数据时,它会将一些法语字符转换为特殊字符。
示例 Être un membre clé
转换为 Être un membre clé
下面的代码用于写入文件
Path path = Paths.get(filePath);
BufferedWriter bw = Files.newBufferedWriter(path);
CSVWriter writer = new CSVWriter(bw);
writer.writeAll(data);
默认使用UTF-8
。
在调试时,我在写入 .csv
之前检查了数据是否原样。但它在写作时会被转换吗?我已将默认区域设置设置为 Locale.FRENCH
我是不是错过了什么?
最佳答案
我怀疑是Excel
将UTF-8
编码的CSV
读取为ANSI
。当您仅在 Excel
中打开 CSV
而不使用文本导入向导时,就会发生这种情况。如果文件开头没有 BOM
,则 Excel
始终期望 ANSI
。如果您使用支持 Unicode
的文本编辑器打开 CSV
,一切都会正确。
示例:
import java.io.BufferedWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import com.opencsv.CSVWriter;
class DocxToCSV {
public static void main(String[] args) throws Exception {
Locale.setDefault(Locale.FRENCH);
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"F1", "F2", "F3", "F4"});
data.add(new String[]{"Être un membre clé", "Être clé", "membre clé"});
data.add(new String[]{"Être", "un", "membre", "clé"});
Path path = Paths.get("test.csv");
BufferedWriter bw = Files.newBufferedWriter(path);
//bw.write(0xFEFF); bw.flush(); // write a BOM to the file
CSVWriter writer = new CSVWriter(bw, ';', '"', '"', "\r\n");
writer.writeAll(data);
writer.flush();
writer.close();
}
}
现在,如果您使用支持 Unicode
的文本编辑器打开 test.csv
,一切都会正确。但如果您使用 Excel
打开同一个文件,它看起来像:
现在我们做同样的事情,但是有
bw.write(0xFEFF); bw.flush(); // write a BOM to the file
活跃。
当 test.csv
只需由 Excel
打开时,Excel
的结果如下:
当然,更好的方法始终是使用 Excel
的 Text Import Wizard .
另请参阅Javascript export CSV encoding utf-8 issue对于同样的问题。
关于java - 字符被转换为特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56705947/