java導出csv格式文件的方法
本文實例為大傢分享瞭java導出csv格式文件的具體代碼,供大傢參考,具體內容如下
導出csv格式文件的本質是導出以逗號為分隔的文本數據
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.alibaba.druid.util.StringUtils; /** * 文件操作 */ public class CSVUtils { /** * 功能說明:獲取UTF-8編碼文本文件開頭的BOM簽名。 * BOM(Byte Order Mark),是UTF編碼方案裡用於標識編碼的標準標記。例:接收者收到以EF BB BF開頭的字節流,就知道是UTF-8編碼。 * @return UTF-8編碼文本文件開頭的BOM簽名 */ public static String getBOM() { byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF}; return new String(b); } /** * 生成CVS文件 * @param exportData * 源數據List * @param map * csv文件的列表頭map * @param outPutPath * 文件路徑 * @param fileName * 文件名稱 * @return */ @SuppressWarnings("rawtypes") public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath, String fileName) { File csvFile = null; BufferedWriter csvFileOutputStream = null; try { File file = new File(outPutPath); if (!file.exists()) { file.mkdirs(); } //定義文件名格式並創建 csvFile =new File(outPutPath+fileName+".csv"); file.createNewFile(); // UTF-8使正確讀取分隔符"," //如果生產文件亂碼,windows下用gbk,linux用UTF-8 csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( csvFile), "UTF-8"), 1024); //寫入前段字節流,防止亂碼 csvFileOutputStream.write(getBOM()); // 寫入文件頭部 for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "" ); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } csvFileOutputStream.newLine(); // 寫入文件內容 for (Iterator iterator = exportData.iterator(); iterator.hasNext();) { Object row = (Object) iterator.next(); for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator .hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator .next(); String str=row!=null?((String)((Map)row).get( propertyEntry.getKey())):""; if(StringUtils.isEmpty(str)){ str=""; }else{ str=str.replaceAll("\"","\"\""); if(str.indexOf(",")>=0){ str="\""+str+"\""; } } csvFileOutputStream.write(str); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } if (iterator.hasNext()) { csvFileOutputStream.newLine(); } } csvFileOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { csvFileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return csvFile; } /** * 生成並下載csv文件 * @param response * @param exportData * @param map * @param outPutPath * @param fileName * @throws IOException */ @SuppressWarnings("rawtypes") public static void exportDataFile(HttpServletResponse response,List exportData, LinkedHashMap map, String outPutPath,String fileName) throws IOException{ File csvFile = null; BufferedWriter csvFileOutputStream = null; try { File file = new File(outPutPath); if (!file.exists()) { file.mkdirs(); } //定義文件名格式並創建 csvFile =new File(outPutPath+fileName+".csv"); if(csvFile.exists()){ csvFile.delete(); } csvFile.createNewFile(); // UTF-8使正確讀取分隔符"," //如果生產文件亂碼,windows下用gbk,linux用UTF-8 csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024); //寫入前段字節流,防止亂碼 csvFileOutputStream.write(getBOM()); // 寫入文件頭部 for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "" ); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } csvFileOutputStream.newLine(); // 寫入文件內容 for (Iterator iterator = exportData.iterator(); iterator.hasNext();) { Object row = (Object) iterator.next(); for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator .hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator .next(); String str=row!=null?((String)((Map)row).get( propertyEntry.getKey())):""; if(StringUtils.isEmpty(str)){ str=""; }else{ str=str.replaceAll("\"","\"\""); if(str.indexOf(",")>=0){ str="\""+str+"\""; } } csvFileOutputStream.write(str); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } if (iterator.hasNext()) { csvFileOutputStream.newLine(); } } csvFileOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { csvFileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } InputStream in = null; try { in = new FileInputStream(outPutPath+fileName+".csv"); int len = 0; byte[] buffer = new byte[1024]; OutputStream out = response.getOutputStream(); response.reset(); response.setContentType("application/csv;charset=UTF-8"); response.setHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(fileName+".csv", "UTF-8")); response.setCharacterEncoding("UTF-8"); while ((len = in.read(buffer)) > 0) { out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); out.write(buffer, 0, len); } out.close(); } catch (FileNotFoundException e) { } finally { if (in != null) { try { in.close(); } catch (Exception e) { throw new RuntimeException(e); } } } } /** * 刪除該目錄filePath下的所有文件 * @param filePath * 文件目錄路徑 */ public static void deleteFiles(String filePath) { File file = new File(filePath); if (file.exists()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { files[i].delete(); } } } } /** * 刪除單個文件 * @param filePath * 文件目錄路徑 * @param fileName * 文件名稱 */ public static void deleteFile(String filePath, String fileName) { File file = new File(filePath); if (file.exists()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { if (files[i].getName().equals(fileName)) { files[i].delete(); return; } } } } } /** * 測試數據 * @param args */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) { List exportData = new ArrayList<Map>(); Map row1 = new LinkedHashMap<String, String>(); row1.put("1", "11"); row1.put("2", "12"); row1.put("3", "13"); row1.put("4", "14"); exportData.add(row1); row1 = new LinkedHashMap<String, String>(); row1.put("1", "21"); row1.put("2", "22"); row1.put("3", "23"); row1.put("4", "24"); exportData.add(row1); LinkedHashMap map = new LinkedHashMap(); //設置列名 map.put("1", "第一列名稱"); map.put("2", "第二列名稱"); map.put("3", "第三列名稱"); map.put("4", "第四列名稱"); //這個文件上傳到路徑,可以配置在數據庫從數據庫讀取,這樣方便一些! String path = "E:/"; //文件名=生產的文件名稱+時間戳 String fileName = "文件導出"; File file = CSVUtils.createCSVFile(exportData, map, path, fileName); String fileName2 = file.getName(); System.out.println("文件名稱:" + fileName2); } }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- JAVA List和Map切割工具詳解
- 關於文件合並與修改md5值的問題
- Java使用迭代器Iterator遍歷集合
- java中壓縮文件並下載的實例詳解
- java中創建寫入文件的6種方式詳解與源碼實例