前两天在书写demo的时候发现导出的csv文件到mac的excle打开是乱码
分析其中原因我概括为
1:导出时候是UTF-8的输出,用文本打开是不会出错的,
2:excle不是UTF-8文本协议,他采用的ASNI编码
关键点就在这里 既然是ASNI就采用 就是一句话的事
bfw.write(0xFEFF);
例子代码
public void ExportToCSV() {
FileWriter fw;
BufferedWriter bfw;
File sdCardDir = Environment.getExternalStorageDirectory();
File saveFile = new File(sdCardDir, "demo.csv");
FinalDb finalDb = EveryDayAccountApplication.getDatabase(mainActivity);
List list = AccountDao.getCostTypeAccount(finalDb);
String[] contents = { "记录备注以及类别", "记录时间", "消费时间", "收入支出", "金额" };
try {
fw = new FileWriter(saveFile);
bfw = new BufferedWriter(fw);
bfw.write(0xFEFF);
System.out.println("daochu"+ contents.length);
for (int i = 0; i < contents.length; i++) {
System.out.println("daochu"+contents[i]);
bfw.write(contents[i] + ",");
}
// 写好表头后换行
bfw.newLine();
// 写入数据
for (Account account : list) {
// 写好每条记录后换行
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",
Locale.CHINA);
String creattime = format.format(account.getCreateTime());
String costtime = format.format(account.getCostTime());
String costName = account.getCostName();
int isCost = account.getIsCost();
double money = account.getMoney();
String arrStr[] = {
costName == null ? "" : costName,
"".equals(creattime) ? "" : creattime,
"".equals(costtime) ? "" : costtime,
isCost == 1 ? "消费" : "收入",
money + "" == null ? "" : money + "" };
for (int i = 0; i < arrStr.length; i++) {
if (i != arrStr.length - 1)
bfw.write(arrStr[i] + ",");
else
bfw.write(arrStr[i]);
}
bfw.newLine();
}
bfw.flush();
bfw.close();
} catch (IOException e) {
e.printStackTrace();
}
}