Java生成CSV文件
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.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; /**
* 文件操作
* @author lizhiyong
* @version $Id: CSVUtils.java, v 0.1
2014年7月22日 下午2:19:59 Exp $
*/
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), "GBK"), 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 ? new String(
((String) propertyEntry.getValue()).getBytes("GBK"), "GBK") : "");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
System.out.println(new String(((String) propertyEntry.getValue()).getBytes("GBK"),
"GBK"));
}
csvFileOutputStream.write("\r\n");
// 写入文件内容
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()) != null? (String) propertyEntry.getKey()
: ""));
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
if (iterator.hasNext()) {
csvFileOutputStream.write("\r\n");
}
}
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=GBK");
response.setHeader("Content-Disposition",
"attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
//URLEncoder.encode(fileName, "GBK") InputStream in = null;
try {
in = new FileInputStream(csvFilePath);
int len = 0;
byte[] buffer = new byte[1024];
response.setCharacterEncoding("GBK");
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文件
<span style="font-family:Courier New;">String name = "工商银行(ICBC)退款数据";
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文件
</span>
版权声明:本文博客原创文章。博客,未经同意,不得转载。
Java生成CSV文件的更多相关文章
- Java生成CSV文件实例详解
本文实例主要讲述了Java生成CSV文件的方法,具体实现步骤如下: 1.新建CSVUtils.java文件: package com.saicfc.pmpf.internal.manage.utils ...
- POI以SAX方式解析Excel2007大文件(包含空单元格的处理) Java生成CSV文件实例详解
http://blog.csdn.net/l081307114/article/details/46009015 http://www.cnblogs.com/dreammyle/p/5458280. ...
- java 生成 csv文件
一.csv文件 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本).纯文本意味着该文件是 ...
- java导出生成csv文件
首先我们需要对csv文件有基础的认识,csv文件类似excel,可以使用excel打开,但是csv文件的本质是逗号分隔的,对比如下图: txt中显示: 修改文件后缀为csv后显示如下: 在java中我 ...
- java 对CSV 文件的读取与生成
CSV文件是以逗号分隔值的文件格式,一般用WORDPAD或记事本(NOTE),EXCEL打开.CSV(逗号分隔值)是一种用来存储数据的纯文本文件,通常都是用于存放电子表格或数据的一种文件格式,对于CS ...
- java将数据生成csv文件
1,httpRequest接口触发进程[或者可以换成其他方式触发] /** * 出入库生成CSV文件 * @param req * @param params * @return */@Request ...
- java 操作 csv文件
CSV是逗号分隔文件(Comma Separated Values)的首字母英文缩写,是一种用来存储数据的纯文本格式,通常用于电子表格或数据库软件.在 CSV文件中,数据“栏”以逗号分隔,可允许程序通 ...
- java读取CSV文件添加到sqlserver数据库
在直接将CSV文件导入sqlserver数据库时出现了错误,原因还未找到,初步怀疑是数据中含有特殊字符.于是只能用代码导数据了. java读取CSV文件的代码如下: package experimen ...
- 图像处理项目——生成csv文件提高读取效率
利用pyhton脚本生成csv文件 *开发环境为windows PyCharm*使用的是pyhton脚本*生成人脸和人脸对应的标签的csv文件 一:主要步骤 1.载入对应路径2.提取每一张图片对应的位 ...
随机推荐
- 使用SVM对于许多类型的多维数据分类
最近,我做了一件小事,使用SVM正确8三维级数据分类,在线搜索,我们发现二分的问题大家都在讨论二维数据,一些决定自己的研究.我首先参考opencvtutorial.这也是二维数据的二分类问题.然后通过 ...
- js多物体任意值运动
假如有两个div,一个div要变宽,一个div要变高,你怎么写呢? 哎呀,写2个方法啊,一个控制div1变宽,一个控制div2变高啊 那么你的代码,是不是下面这样的呢! 示例:Div变宽和变高 现象: ...
- 使用Intel HAXM 加速你的Android模拟器
Android 模拟器一直以运行速度慢著称, 本文介绍使用 Intel HAXM 技术为 Android 模拟器加速, 使模拟器运行度媲美真机, 彻底解决模拟器运行慢的问题. Intel HAXM ( ...
- css--左右visibility建立 “collapse”值问题
1.您可能已使用visibility一千次,最常用的是visible和hidden.它用来显示或隐藏元素. 有第三很少已使用的值它是collapse,在表格的行,列中使用有差异外,他和hidden的作 ...
- php 两个文件之间的相对路径的计算方法
php 两个文件之间的相对路径的计算方法 比如: 文件A 的路径是 /home/web/lib/img/cache.php 文件B的路径是 /home/web/api/img/show.php 那么. ...
- [LeetCode116]Path Sum
题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...
- Webx框架:Valve详细解释
Valve请求,用于控制过程的操作.它采用责任设计模式链(类别似至struts拦截器).valve阀装置,阀控制水流量(网络请求)趋势. 他们阀门定义. public class MyValve im ...
- 探索Windows Azure 监控和自动伸缩系列2 - 获取虚拟机的监控定义和监控数据
上一篇博文介绍了如何连接Windows Azure: http://www.cnblogs.com/teld/p/5113063.html 本篇我们继续上次的示例代码,获取虚拟机的监控定义和监控数据. ...
- IE8/IE9无法启用JavaScript怎么办
在IE8/IE9 中,有些同学在浏览网页时,收到提示:“需要启用 JavaScript …”,并且会发现网页上某些功能不能用了,比如点击网页里的按钮没反应等等.这个是因为浏览器的JavaScript ...
- Redis源代码分析(二十八)--- object创建和释放redisObject物
今天的学习更有效率.该Rio分析过,学习之间的另一种方式RedisObject文件,只想说RedisObject有些生成和转换.都是很类似的.列出里面长长的API列表: /* ------------ ...