Java生成CSV文件實(shí)例詳解
本文實(shí)例主要講述了Java生成CSV文件的方法,具體實(shí)現(xiàn)步驟如下:
1、新建CSVUtils.java文件:
package com.saicfc.pmpf.internal.manage.utils;
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 org.apache.commons.beanutils.BeanUtils;
/**
* 文件操作
*/
public class CSVUtils {
/**
* 生成為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.mkdir();
}
//定義文件名格式并創(chuàng)建
csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
System.out.println("csvFile:" + csvFile);
// UTF-8使正確讀取分隔符","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
csvFile), "UTF-8"), 1024);
System.out.println("csvFileOutputStream:" + csvFileOutputStream);
// 寫入文件頭部
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();
csvFileOutputStream.write((String) BeanUtils.getProperty(row,
(String) propertyEntry.getKey()));
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;
}
/**
* 下載文件
* @param response
* @param csvFilePath
* 文件路徑
* @param fileName
* 文件名稱
* @throws IOException
*/
public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName)
throws IOException {
response.setContentType("application/csv;charset=UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream in = null;
try {
in = new FileInputStream(csvFilePath);
int len = 0;
byte[] buffer = new byte[1024];
response.setCharacterEncoding("UTF-8");
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
System.out.println(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();
map.put("1", "第一列");
map.put("2", "第二列");
map.put("3", "第三列");
map.put("4", "第四列");
String path = "c:/export/";
String fileName = "文件導(dǎo)出";
File file = CSVUtils.createCSVFile(exportData, map, path, fileName);
String fileName2 = file.getName();
System.out.println("文件名稱:" + fileName2);
}
}
2、調(diào)用createCSVFile方法生成CSV文件
String name = "銀行退款數(shù)據(jù)";
List exportData = new ArrayList();
LinkedHashMap datamMap = null;
for (Iterator iterator = refundList.iterator(); iterator.hasNext();) {
HashMap map = (HashMap) iterator.next();
datamMap = new LinkedHashMap();
datamMap.put("1", map.get("merOrderId"));
datamMap.put("2",DateUtil.convertDateToString("yyyyMMdd", (Date) map.get("orderTime")));
BigDecimal amount = (BigDecimal) map.get("amount");
String amountString = amount.divide(new BigDecimal(10)).toPlainString();
datamMap.put("3", amountString);
datamMap.put("4", map.get("remark") != null ? map.get("remark") : "");
exportData.add(datamMap);
}
LinkedHashMap map = new LinkedHashMap();
map.put("1", "訂單號(hào)");
map.put("2", "支付日期");
map.put("3", "退貨現(xiàn)金金額(整數(shù)金額 單位:分)");
map.put("4", "退貨原因");
File file = CSVUtils.createCSVFile(exportData, map, filePath, name);//生成CSV文件
fileName = file.getName();
CSVUtils.exportFile(response, filePath + fileName, fileName);//下載生成的CSV文件
相關(guān)文章
Java function函數(shù)式接口的使用方法與實(shí)例
這篇文章主要介紹了Java function函數(shù)式接口的使用方法與實(shí)例,函數(shù)式接口如一支未完成的詩篇,用Lambda表達(dá)式作韻腳,將代碼的機(jī)械美感與藝術(shù)的抽象融為一體,悄然重構(gòu)了開發(fā)者對(duì)代碼之美的認(rèn)知,需要的朋友可以參考下2025-02-02
Kotlin開發(fā)Android應(yīng)用實(shí)例詳解
這篇文章主要介紹了Kotlin開發(fā)Android應(yīng)用實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
SpringSecurity進(jìn)行認(rèn)證與授權(quán)的示例代碼
SpringSecurity是Spring家族中的一個(gè)安全管理框架,而認(rèn)證和授權(quán)也是SpringSecurity作為安全框架的核心功能,本文主要介紹了SpringSecurity進(jìn)行認(rèn)證與授權(quán)的示例代碼,感興趣的可以了解一下2024-06-06
Servlet實(shí)現(xiàn)點(diǎn)擊計(jì)數(shù)器的方法
這篇文章主要介紹了Servlet實(shí)現(xiàn)點(diǎn)擊計(jì)數(shù)器的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-08-08
Zuul 實(shí)現(xiàn)網(wǎng)關(guān)轉(zhuǎn)發(fā)的五種方式小結(jié)
這篇文章主要介紹了Zuul 實(shí)現(xiàn)網(wǎng)關(guān)轉(zhuǎn)發(fā)的五種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Java開發(fā)如何把數(shù)據(jù)庫里的未付款訂單改成已付款
這篇文章主要介紹了Java開發(fā)如何把數(shù)據(jù)庫里的未付款訂單改成已付款,先介紹MD5算法,簡(jiǎn)單的來說,MD5能把任意大小、長(zhǎng)度的數(shù)據(jù)轉(zhuǎn)換成固定長(zhǎng)度的一串字符,實(shí)現(xiàn)思路非常簡(jiǎn)單需要的朋友可以參考下2022-11-11
基于Java SSM框架開發(fā)圖書借閱系統(tǒng)源代碼
本文給大家介紹了基于Java SSM框架開發(fā)圖書借閱系統(tǒng),開發(fā)環(huán)境基于idea2020+mysql數(shù)據(jù)庫,前端框架使用bootstrap4框架,完美了實(shí)現(xiàn)圖書借閱系統(tǒng),喜歡的朋友快來體驗(yàn)吧2021-05-05
使用restTemplate遠(yuǎn)程調(diào)controller路徑取數(shù)據(jù)
這篇文章主要介紹了使用restTemplate遠(yuǎn)程調(diào)controller路徑取數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08

