android导出CSV,中文乱码问题

来源:互联网 发布:抑郁症测试 知乎 编辑:程序博客网 时间:2024/06/06 10:56

前两天在书写demo的时候发现导出的csv文件到mac的excle打开是乱码


分析其中原因我概括为 

1:导出时候是UTF-8的输出,用文本打开是不会出错的,

2:excle不是UTF-8文本协议,他采用的ASNI编码


关键点就在这里 既然是ASNI就采用  就是一句话的事

<strong>bfw.write(0xFEFF);</strong>




       例子代码

<pre name="code" class="java">public void ExportToCSV() {FileWriter fw;BufferedWriter bfw;File sdCardDir = Environment.getExternalStorageDirectory();File saveFile = new File(sdCardDir, "demo.csv");FinalDb finalDb = EveryDayAccountApplication.getDatabase(mainActivity);List<Account> 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] + ",");elsebfw.write(arrStr[i]);}bfw.newLine();}bfw.flush();bfw.close();} catch (IOException e) {e.printStackTrace();}}


0 0