Java實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)到csv文件的示例代碼
項(xiàng)目中很多情況會(huì)遇到需要導(dǎo)出數(shù)據(jù)到csv文件,代碼如下:
package com.elane.common.utils.poi; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.List; public class CSVUtil { /** * 導(dǎo)出csv文件 * @param response 導(dǎo)出文件需要的設(shè)置在response 中設(shè)置好 * @param head 英文逗號(hào)分隔的數(shù)據(jù)表頭 * @param dataList 英文逗號(hào)分隔的數(shù)據(jù) * @param filename 導(dǎo)出后的文件名稱 */ public static void createCSVFile(HttpServletResponse response, List<String> head, List<String> dataList, String filename) { File csvFile = null; BufferedWriter csvWtriter = null; InputStream in = null; OutputStream out = null; try { csvFile=new File(filename); // GB2312使正確讀取分隔符"," FileOutputStream fileOutputStream=new FileOutputStream(csvFile); OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream); // outputStreamWriter.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF})); csvWtriter = new BufferedWriter(outputStreamWriter); // 寫(xiě)入文件頭部 if (head.size()>0){ csvWtriter.write(head.get(0)); csvWtriter.newLine(); } // 寫(xiě)入文件內(nèi)容 for (String item:dataList){ csvWtriter.write(item); csvWtriter.newLine(); } csvWtriter.flush(); in = new FileInputStream(csvFile); int len = 0; byte[] buffer = new byte[1024*1024*5]; out = response.getOutputStream(); // 設(shè)置此response為文件下載響應(yīng) response.setContentType("application/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(csvFile.getName(), "UTF-8")); response.setCharacterEncoding("UTF-8"); // 先寫(xiě)UTF-8文件標(biāo)志頭 out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (csvFile != null) { csvFile.delete(); } if (csvWtriter != null) { csvWtriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 保存至csv文件,不導(dǎo)出 * @param fileName 保存的文件名 * @param tempDir 文件保存路徑 * @param head 英文逗號(hào)分隔的數(shù)據(jù)表頭 * @param dataList 英文逗號(hào)分隔的數(shù)據(jù) */ public static void SaveTxtFile(String fileName, String tempDir,List<String> head,List<String> dataList) { String filePath=tempDir+"/"+fileName; try{ FileOutputStream fileOutputStream=new FileOutputStream(filePath); OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream); outputStreamWriter.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF})); BufferedWriter writer=new BufferedWriter(outputStreamWriter); writer.write(head.get(0)); writer.newLine(); for (String item:dataList){ writer.write(item)); writer.newLine(); } writer.close(); } catch (IOException e){ System.err.println(e.getMessage()); } } }
方法補(bǔ)充
1.java導(dǎo)出csv格式文件
導(dǎo)出csv格式文件的本質(zhì)是導(dǎo)出以逗號(hào)為分隔的文本數(shù)據(jù)
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 { /** * 功能說(shuō)明:獲取UTF-8編碼文本文件開(kāi)頭的BOM簽名。 * BOM(Byte Order Mark),是UTF編碼方案里用于標(biāo)識(shí)編碼的標(biāo)準(zhǔn)標(biāo)記。例:接收者收到以EF BB BF開(kāi)頭的字節(jié)流,就知道是UTF-8編碼。 * @return UTF-8編碼文本文件開(kāi)頭的BOM簽名 */ public static String getBOM() { byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF}; return new String(b); } /** * 生成CVS文件 * @param exportData * 源數(shù)據(jù)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(); } //定義文件名格式并創(chuàng)建 csvFile =new File(outPutPath+fileName+".csv"); file.createNewFile(); // UTF-8使正確讀取分隔符"," //如果生產(chǎn)文件亂碼,windows下用gbk,linux用UTF-8 csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( csvFile), "UTF-8"), 1024); //寫(xiě)入前段字節(jié)流,防止亂碼 csvFileOutputStream.write(getBOM()); // 寫(xiě)入文件頭部 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(); // 寫(xiě)入文件內(nèi)容 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(); } //定義文件名格式并創(chuàng)建 csvFile =new File(outPutPath+fileName+".csv"); if(csvFile.exists()){ csvFile.delete(); } csvFile.createNewFile(); // UTF-8使正確讀取分隔符"," //如果生產(chǎn)文件亂碼,windows下用gbk,linux用UTF-8 csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024); //寫(xiě)入前段字節(jié)流,防止亂碼 csvFileOutputStream.write(getBOM()); // 寫(xiě)入文件頭部 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(); // 寫(xiě)入文件內(nèi)容 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(); } } } } /** * 刪除單個(gè)文件 * @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; } } } } } /** * 測(cè)試數(shù)據(jù) * @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(); //設(shè)置列名 map.put("1", "第一列名稱"); map.put("2", "第二列名稱"); map.put("3", "第三列名稱"); map.put("4", "第四列名稱"); //這個(gè)文件上傳到路徑,可以配置在數(shù)據(jù)庫(kù)從數(shù)據(jù)庫(kù)讀取,這樣方便一些! String path = "E:/"; //文件名=生產(chǎn)的文件名稱+時(shí)間戳 String fileName = "文件導(dǎo)出"; File file = CSVUtils.createCSVFile(exportData, map, path, fileName); String fileName2 = file.getName(); System.out.println("文件名稱:" + fileName2); } }
2.Java實(shí)現(xiàn)Csv文件導(dǎo)入導(dǎo)出
導(dǎo)入
/** * 讀取crv文件并轉(zhuǎn)換成List * * @param separator crv文件分隔符 * @param file 待讀取文件 * @return crv對(duì)象list */ public static <T> List<T> read(String separator, File file, Class<T> clazz) { List<T> result = Collections.emptyList(); try { BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz); //設(shè)置分隔符 CsvFormat csvFormat = new CsvFormat(); csvFormat.setDelimiter(separator); CsvParserSettings parserSettings = new CsvParserSettings(); parserSettings.setProcessor(rowProcessor); parserSettings.setFormat(csvFormat); CsvParser parser = new CsvParser(parserSettings); InputStream in = Files.newInputStream(file.toPath()); parser.parse(in); //逐行讀取 result = rowProcessor.getBeans(); } catch (Exception e) { log.error("Import csv file failed. message: ", e); } return result; }
測(cè)試
@Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public static class User implements Serializable { @Parsed(filed = "name") private String name; @Parsed(filed = "age") private Integer age; } public static void main(String[] args) { File file = new File("E:\\test.csv"); List<User> users = CsvUtil.read(",", file, User.class); users.forEach(System.out::println); }
導(dǎo)出
直接創(chuàng)建一個(gè)工具類使用,把導(dǎo)入導(dǎo)出方法粘貼進(jìn)去使用即可
/** * csv文件導(dǎo)出 * * @param data 導(dǎo)出數(shù)據(jù) * @param file 導(dǎo)出目的文件 * @param separator 分割符 * @param clazz 導(dǎo)出對(duì)象 * @param <T> 數(shù)據(jù)對(duì)象泛型 */ public static <T> void export(Collection<T> data, File file, String separator, Class<T> clazz) { try { CsvWriterSettings settings = new CsvWriterSettings(); //設(shè)置分隔符 CsvFormat csvFormat = new CsvFormat(); csvFormat.setDelimiter(separator); settings.setFormat(csvFormat); settings.setHeaderWritingEnabled(false); settings.setRowWriterProcessor(new BeanWriterProcessor<>(clazz)); CsvWriter writer = new CsvWriter(Files.newOutputStream(file.toPath()), "utf-8", settings); // 寫(xiě)入header writer.writeHeaders(settings.getHeaders()); data.forEach(writer::processRecord); writer.close(); } catch (Exception e) { log.error("export .csv file failed. message.", e); } }
測(cè)試
@Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public static class User implements Serializable { @Parsed(filed = "name") private String name; @Parsed(filed = "age") private Integer age; } public static void main(String[] args) { User user1 = new User("張三", 18); User user2 = new User("李四", 19); List<User> users = Arrays.asList(user1, user2); File file = new File("E:\\test.csv"); CsvUtil.export(users, file, ",", User.class); }
到此這篇關(guān)于Java實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)到csv文件的示例代碼的文章就介紹到這了,更多相關(guān)Java導(dǎo)出數(shù)據(jù)到csv內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot集成elasticsearch7的圖文方法
本文記錄springboot集成elasticsearch7的方法,本文通過(guò)圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-05-05解決Mybatis?mappe同時(shí)傳遞?List?和其他參數(shù)報(bào)錯(cuò)的問(wèn)題
在使用MyBatis時(shí),如果需要傳遞多個(gè)參數(shù)到SQL中,可以遇到參數(shù)綁定問(wèn)題,解決方法包括使用@Param注解和修改mapper.xml配置,感興趣的朋友跟隨小編一起看看吧2024-09-09Java簡(jiǎn)易抽獎(jiǎng)系統(tǒng)小項(xiàng)目
這篇文章主要為大家詳細(xì)介紹了Java簡(jiǎn)易抽獎(jiǎng)系統(tǒng)小項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01基于SpringBoot+vue實(shí)現(xiàn)前后端數(shù)據(jù)加解密
這篇文章主要給大家介紹了基于SpringBoot+vue實(shí)現(xiàn)前后端數(shù)據(jù)加解密,文中有詳細(xì)的示例代碼,具有一定的參考價(jià)值,感興趣的小伙伴可以自己動(dòng)手試一試2023-08-08SpringBoot項(xiàng)目中通過(guò)@Value給參數(shù)賦值失敗的解決方案
springboot項(xiàng)目中通過(guò)@Value給屬性附值失敗,給參數(shù)賦值失敗,打印為空值,文中通過(guò)代碼示例給大家介紹的非常詳細(xì),對(duì)大家解決問(wèn)題有一定的幫助,需要的朋友可以參考下2024-04-04關(guān)于@SpringBootApplication與@SpringBootTest的區(qū)別及用法
這篇文章主要介紹了關(guān)于@SpringBootApplication與@SpringBootTest的區(qū)別及用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01jackson json序列化實(shí)現(xiàn)首字母大寫(xiě),第二個(gè)字母需小寫(xiě)
這篇文章主要介紹了jackson json序列化實(shí)現(xiàn)首字母大寫(xiě),第二個(gè)字母需小寫(xiě)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06