Java生成CSV文件实例详解
本文实例主要讲述了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.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文件
public static void main(String[] args) {
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文件
}
本文转自:http://www.jb51.net/article/52724.htm
Java生成CSV文件实例详解的更多相关文章
- POI以SAX方式解析Excel2007大文件(包含空单元格的处理) Java生成CSV文件实例详解
http://blog.csdn.net/l081307114/article/details/46009015 http://www.cnblogs.com/dreammyle/p/5458280. ...
- Java生成CSV文件
1.新CSVUtils.java文件: package com.saicfc.pmpf.internal.manage.utils; import java.io.BufferedWriter; im ...
- Java中JSON字符串与java对象的互换实例详解
这篇文章主要介绍了在java中,JSON字符串与java对象的相互转换实例详解,非常不错,具有参考借鉴价值,需要的朋友可以参考下 在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JS ...
- Java中JSON字符串与java对象的互换实例详解(转)
http://www.jb51.net/article/90914.htm 在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级的数据格式比xml效率要 ...
- Java开发之I/O读取文件实例详解
在java开发或者android开发中,读取文件是不可避免的,以下对java开发中读取文件做了归纳和详解: 1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容 4.随机读取文件内容 pa ...
- java 生成 csv文件
一.csv文件 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本).纯文本意味着该文件是 ...
- 运行java的class文件方法详解
一.运行class文件 执行带main方法的class文件,命令行为:java <CLASS文件名>注意:CLASS文件名不要带文件后缀.class 例如: 复制代码代码如下: java ...
- php 读取功能分割大文件实例详解
在php中,对于文件的读取时,最快捷的方式莫过于使用一些诸如file.file_get_contents之类的函数.但当所操作的文件是一个比较大的文件时,这些函数可能就显的力不从心, 下面将从一个需求 ...
- (转)Java中JSON字符串与java对象的互换实例详解
在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML.JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好, ...
随机推荐
- [Java][Weblogic] weblogic.net.http.SOAPHttpsURLConnection incompatible with javax.net.ssl.HttpsURLConnection解决办法
更新20141120: 我始终对修改生产上weblogic上的配置文件这一方法心存担忧(生产上的服务器不允许随便修改,可能会影响到其他应用),所以想使用代码的方式解决此问题,在对方法一失败原因进行了进 ...
- PL/SQL Developer 9.x 注册码
记下来,以备以后使用,好笔头,哈哈哈 Product Code:46jw8l8ymfmp2twwbuur8j9gv978m2q2du serial Number:307254 password:xs3 ...
- [荐]使用Js操作注册表
使用Js操作注册表 要操作注册表需要通过ActiveX控件调用WScript.shell对象,通过该对象的一些方法来操作. WshShell对象:可以在本地运行程序.操纵注册表内容.创建快捷方式或访问 ...
- iOS开发资料链接
ios开发中文文档了 http://developer.apple.com/library/ios/#referencelibrary/GettingStarted/RoadMapiOSCh/chap ...
- Hibernate 延迟加载
一.什么是延迟加载? 延迟加载是指当应用程序想要从数据库获取对象时(在没有设置lazy属性值为false),Hibernate只是从数据库获取符合条件的对象的OId从而生成代理对象,并没有加载出对象访 ...
- 使用JdbcTemplate报 Incorrect column count: expected 1, actual 5错误解决
Incorrect column count: expected 1, actual 5 在使用jdbc的querForObject queryForList的时候,出现Incorrect colum ...
- 解决:未能加载文件或程序集“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”
使用nuget管理程序包,有可能在不同时间安装不同版本的Entity Framework:在项目创建初期安装的是6.0.0.0版本,后来添加的类库,安装了6.1.1版本,所以出现这个问题. 解决办法: ...
- BFS+Hash(储存,判重) HDOJ 1067 Gap
题目传送门 题意:一个图按照变成指定的图,问最少操作步数 分析:状态转移简单,主要是在图的存储以及判重问题,原来队列里装二维数组内存也可以,判重用神奇的hash技术 #include <bits ...
- Mvc网站发布到IIS
网站发布步骤: 这部分是转载文章 在此标明出处,以前有文章是转的没标明的请谅解,因为有些已经无法找到出处,或者与其它原因. 如有冒犯请联系本人,或删除,或标明出处. 因为好的文章,以前只想收藏,但连接 ...
- Zend studio 10.6 配置XDEBUG
1. 查看PHP版本,下载XDebug 然后去网站http://xdebug.org/download.php下载相应的XDEBUG, 把下载好的文件放到相应的PHP下的EXT目录下,替换之前 ...