/*** CSV文件生成方法* @param head 文件头* @param dataList 数据列表* @param outPutPath 文件输出路径* @param filename 文件名* @return*/public static File createCSVFile(List<String> head, List<List<String>> dataList,String outPutPath, String filename) {File csvFile = null;BufferedWriter csvWtriter = null;try {csvFile = new File(outPutPath + File.separator + filename + ".csv");File parent = csvFile.getParentFile();if (parent != null && !parent.exists()) {parent.mkdirs();}csvFile.createNewFile();// GB2312使正确读取分隔符","FileOutputStream fileOutputStream = new FileOutputStream(csvFile);byte [] bs = { (byte)0xEF, (byte)0xBB, (byte)0xBF};fileOutputStream.write(bs);csvWtriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));//csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(// csvFile),"GB2312"),1024);//csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(// csvFile),"utf-8"),1024);//Map map = new HashMap<>();//map.put("head", head);// 写入文件头部writeRow(head, csvWtriter);// 写入文件内容for (List<String> row : dataList) {writeRow(row, csvWtriter);}csvWtriter.flush();} catch (Exception e) {e.printStackTrace();} finally {try {csvWtriter.close();} catch (IOException e) {e.printStackTrace();}}return csvFile;}/*** 写一行数据方法* @param row* @param csvWriter* @throws IOException*/private static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {// 写入文件头部for (String data : row) {StringBuffer sb = new StringBuffer();//String rowStr = sb.append("\"").append(data).append("\",").toString();String rowStr = sb.append(data).append(",").toString();csvWriter.write(rowStr);}csvWriter.newLine();}public static void main(String[] args) {List<String> exportData = new ArrayList<>();exportData.add("第一列");exportData.add("第二列");exportData.add("第三列");List<List<String>> datalist = new ArrayList<>();List<String> data = new ArrayList<>();data.add("111");data.add("222");data.add("333");List<String> data1 = new ArrayList<>();data1.add("444");data1.add("555");data1.add("666");datalist.add(data);datalist.add(data1);String path = "C:/Users/Desktop";String fileName = "10";File file = createCSVFile(exportData, datalist, path, fileName);String fileName2 = file.getName();System.out.println("文件名称:" + fileName2);}
windows系统中文本文档的编码格式用BOM来指定,在文件的开头要写入字符:EF BB BF(UTF-8的BOM编码),这样UTF-8编码的文件才能被正确识别。
关于BOM
BOM(byte-order mark),即字节顺序标记,用于标记字节序的,也就是大小端。UTF- 8以字节为编码单元,没有字节序的问题,因此UTF-8不需要BOM来表明字节顺序,但可以用BOM来表明编码方式,在Windows系统中就是使用BOM来标记文本文件的编码方式的。UTF- 8的BOM编码是EF BB BF,Excel发现文件开头的EF BB BF就知道文件编码方式是UTF- 8,因此就能正常显示中文。