Java實現(xiàn)導(dǎo)出數(shù)據(jù)到csv文件的示例代碼
項目中很多情況會遇到需要導(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 英文逗號分隔的數(shù)據(jù)表頭
* @param dataList 英文逗號分隔的數(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);
// 寫入文件頭部
if (head.size()>0){
csvWtriter.write(head.get(0));
csvWtriter.newLine();
}
// 寫入文件內(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");
// 先寫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 英文逗號分隔的數(shù)據(jù)表頭
* @param dataList 英文逗號分隔的數(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());
}
}
}方法補充
1.java導(dǎo)出csv格式文件
導(dǎo)出csv格式文件的本質(zhì)是導(dǎ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 {
/**
* 功能說明:獲取UTF-8編碼文本文件開頭的BOM簽名。
* BOM(Byte Order Mark),是UTF編碼方案里用于標(biāo)識編碼的標(biāo)準(zhǔn)標(biāo)記。例:接收者收到以EF BB BF開頭的字節(jié)流,就知道是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
* 源數(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);
//寫入前段字節(jié)流,防止亂碼
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();
// 寫入文件內(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);
//寫入前段字節(jié)流,防止亂碼
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();
// 寫入文件內(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();
}
}
}
}
/**
* 刪除單個文件
* @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;
}
}
}
}
}
/**
* 測試數(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", "第四列名稱");
//這個文件上傳到路徑,可以配置在數(shù)據(jù)庫從數(shù)據(jù)庫讀取,這樣方便一些!
String path = "E:/";
//文件名=生產(chǎn)的文件名稱+時間戳
String fileName = "文件導(dǎo)出";
File file = CSVUtils.createCSVFile(exportData, map, path, fileName);
String fileName2 = file.getName();
System.out.println("文件名稱:" + fileName2);
}
} 2.Java實現(xiàn)Csv文件導(dǎo)入導(dǎo)出
導(dǎo)入
/**
* 讀取crv文件并轉(zhuǎn)換成List
*
* @param separator crv文件分隔符
* @param file 待讀取文件
* @return crv對象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;
}
測試
@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)建一個工具類使用,把導(dǎo)入導(dǎo)出方法粘貼進去使用即可
/**
* csv文件導(dǎo)出
*
* @param data 導(dǎo)出數(shù)據(jù)
* @param file 導(dǎo)出目的文件
* @param separator 分割符
* @param clazz 導(dǎo)出對象
* @param <T> 數(shù)據(jù)對象泛型
*/
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);
// 寫入header
writer.writeHeaders(settings.getHeaders());
data.forEach(writer::processRecord);
writer.close();
} catch (Exception e) {
log.error("export .csv file failed. message.", e);
}
}
測試
@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實現(xiàn)導(dǎo)出數(shù)據(jù)到csv文件的示例代碼的文章就介紹到這了,更多相關(guān)Java導(dǎo)出數(shù)據(jù)到csv內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot集成elasticsearch7的圖文方法
本文記錄springboot集成elasticsearch7的方法,本文通過圖文實例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-05-05
解決Mybatis?mappe同時傳遞?List?和其他參數(shù)報錯的問題
在使用MyBatis時,如果需要傳遞多個參數(shù)到SQL中,可以遇到參數(shù)綁定問題,解決方法包括使用@Param注解和修改mapper.xml配置,感興趣的朋友跟隨小編一起看看吧2024-09-09
基于SpringBoot+vue實現(xiàn)前后端數(shù)據(jù)加解密
這篇文章主要給大家介紹了基于SpringBoot+vue實現(xiàn)前后端數(shù)據(jù)加解密,文中有詳細(xì)的示例代碼,具有一定的參考價值,感興趣的小伙伴可以自己動手試一試2023-08-08
SpringBoot項目中通過@Value給參數(shù)賦值失敗的解決方案
springboot項目中通過@Value給屬性附值失敗,給參數(shù)賦值失敗,打印為空值,文中通過代碼示例給大家介紹的非常詳細(xì),對大家解決問題有一定的幫助,需要的朋友可以參考下2024-04-04
關(guān)于@SpringBootApplication與@SpringBootTest的區(qū)別及用法
這篇文章主要介紹了關(guān)于@SpringBootApplication與@SpringBootTest的區(qū)別及用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
jackson json序列化實現(xiàn)首字母大寫,第二個字母需小寫
這篇文章主要介紹了jackson json序列化實現(xiàn)首字母大寫,第二個字母需小寫方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

