您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關使用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); } }
關于使用java怎么導出csv格式的文件就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。