本文实例主要讲述了Java生成CSV文件的方法,具体实现步骤如下:
1、新建CSVUtils.java文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
|
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
* 源数据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();
}
//定义文件名格式并创建
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();
// 写入文件内容
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();
}
}
}
}
/**
* 删除单个文件
* @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 =
"c:/export/"
;
String fileName =
"文件导出"
;
File file = CSVUtils.createCSVFile(exportData, map, path, fileName);
String fileName2 = file.getName();
System.out.println(
"文件名称:"
+ fileName2);
}
}
|
2、调用createCSVFile方法生成CSV文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
String name =
"银行退款数据"
;
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"
,
"订单号"
);
map.put(
"2"
,
"支付日期"
);
map.put(
"3"
,
"退货现金金额(整数金额 单位:分)"
);
map.put(
"4"
,
"退货原因"
);
File file = CSVUtils.createCSVFile(exportData, map, filePath, name);
//生成CSV文件
fileName = file.getName();
CSVUtils.exportFile(response, filePath + fileName, fileName);
//下载生成的CSV
|