生成csv文件时的一个坑
1、先上个预期的结果图:结果文件有三列,表头分别为id,Name,Desc
2、再上一段生成上述csv的代码:package chapter4;import java.io.File;import java.io.FileWriter;import java.io.IO呶蓟鹭毵Exception;import java.util.ArrayList;import java.util.List;/** * Created by MyWorld on 2016/3/23. */public class CsvWriter { public static void main(String[] args) throws IOException { List<String> source = getResult(); CsvWriter csvWriter = new CsvWriter(); csvWriter.write(source); } private static List<String> getResult() { String title = "id,Name,Desc"; List<String> source = new ArrayList<String>(); source.add(title); source.add(String.format("1,Tom,%s", "My name is tom.")); source.add(String.format("2,Jim,%s", "My name is Jim,twenty years old")); source.add(String.format("3,John,%s", "My name is John.Hello!")); return source; } public void write(List<String> source) throws IOException { File file = new File("result.csv"); System.out.println(file.getAbsolutePath()); FileWriter fw = new FileWriter(file); for (String line : source) { fw.write(String.format("%s \n", line)); } fw.flush(); fw.close(); }}
3、执行上述代码,看看生成的结果文件是什么样的。咦,怎么第三行的“twenty years old”到第四列了
4、看看原因:id,Name,Desc1,Tom,My name is tom.2,Jim,My name is Jim,twenty years old3,John,My name is John.Hello!
5、原来,每二行记录的第三列的字符串中有英文逗号,而csv格式的文件是使用英文逗号分隔不同字段值的。罕铞泱殳csv解弗幺黑镯析器在展示csv文件的内容时,把“twenty years old”展示到第四列了解决办法:给第三列字符串加双引号更改代码,因为字符串外面已经有双引号了,需要将添加的双引号进行转义Code:source.add(String.format("2,Jim,\"%s\"", "My name is Jim,twenty years old"));
6、看看生成的结果与实际是否一致是一致的!!OK