1、设置setContentType为application/x-msdownload
2、设置Content-Disposition为附件形式并指定文件名称attachment;filename=contact.csv
3、根据文件路径创建输入流,response获取输出流
4、写入到输出流
5、删除缓存文件
6、关闭流
@RequestMapping(value = "/exportContact", method = RequestMethod.GET)
private void exportContact(HttpServletRequest request, HttpServletResponse response) {
DBObject query = new BasicDBObject();
String loginEmail = null;
DataOutputStream os = null;
InputStream is = null;
String contactPath = null;
try {
//TODO:登录人信息,目前从配置文件中读取登陆人邮箱
loginEmail = PropertyUtil.getMailProperties().getProperty("mail.email");
query.put("emailAccount", loginEmail);
//取得收件箱所有数据
List list = wmPerService.getData(WmPerConstant.MONGODB_COLLECTION_CONTACT, query);
List contacts = new ArrayList();
for (DBObject entity : list) {
String json = entity.toString();
WmPerInfoDTO wmPerInfo = com.alibaba.fastjson.JSON.parseObject(json, WmPerInfoDTO.class);
String[] contact =
{
wmPerInfo.getPerName(),
wmPerInfo.getPerEmail(),
wmPerInfo.getPerPhone(),
wmPerInfo.getPerProvinceName(),
wmPerInfo.getPerCityName(),
wmPerInfo.getPerCountyName(),
wmPerInfo.getPerStreetName(),
wmPerInfo.getPerDetailAddrss(),
wmPerInfo.getPerRemark()
};
// {"姓名", "邮箱地址", "手机号码", "省", "市", "县/区", "乡镇/街道", "详细地址", "备注"};
contacts.add(contact);
}
contactPath = CVSUtils.writeCsv(loginEmail, contacts);
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=contact.csv");
is = new BufferedInputStream(new FileInputStream(contactPath));
if (null != is){
os = new DataOutputStream(response.getOutputStream());
IOUtils.copy(is, os);
os.flush();
}
} catch (Exception e) {
logger.error("当前下载的附件不存在,或者下载附件错误", e);
}
finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
File file = new File(contactPath);
file.delete();
}
}
CSVUtils.java
/**
* CSV文件导出工具类
*/
public class CVSUtils {
public static final String FILE_EXTENSIONS = ".csv";
public static final String CONTACT_FOLDER = "contact";
public static final String CONTACT_PATH = CVSUtils.class.getClassLoader().getResource("/").getPath();
public static final String[] heads = {"姓名", "邮箱地址", "手机号码", "省", "市", "县/区", "乡镇/街道", "详细地址", "备注"};
//读取csv文件
public static List readCsv(String filePath) throws Exception {
List csvList = new ArrayList();
if (isCsv(filePath)) {
CsvReader reader = new CsvReader(filePath, ',', Charset.forName("GBK"));
while (reader.readRecord()) { //逐行读入除表头的数据
csvList.add(reader.getValues());
}
reader.close();
} else {
System.out.println("此文件不是CSV文件!");
throw new RuntimeException("此文件不是CSV文件!");
}
return csvList;
}
//判断是否是csv文件
private static boolean isCsv(String fileName) {
return fileName.matches("^.+\\.(?i)(csv)$");
}
//写入csv文件并返回文件路径
public static String writeCsv(String fileName, List contents) {
try {
String filePath = CONTACT_PATH.substring(0, CONTACT_PATH.length() - 8);
String fileNameTemp = System.currentTimeMillis() + fileName + FILE_EXTENSIONS;
String fileQualifiedName = filePath + CONTACT_FOLDER + File.separator + fileNameTemp;
File csvFile = new File(fileQualifiedName);
File parent = csvFile.getParentFile();//得到父目录
if (parent != null && !parent.exists()) {
parent.mkdirs();//创建文件夹
}
csvFile.createNewFile();//创建具体的文件
CsvWriter wr = new CsvWriter(fileQualifiedName, ',', Charset.forName("GBK"));
wr.writeRecord(heads);
if (contents != null && contents.size() > 0) {
for (String[] content : contents) {
wr.writeRecord(content);
}
}
wr.close();
return fileQualifiedName;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// public static void writeCsv(Class> clazz) {
// // Get all the declared fields
// Field[] fields = clazz.getDeclaredFields();
// LinkedList fieldList = new LinkedList();
// int length = fields.length;
// for (int i = -1; ++i < length; ) {
// boolean isStaticField = Modifier.isStatic(fields[i].getModifiers());
// if (isStaticField)
// continue;
// boolean isTransientField = Modifier.isTransient(fields[i].getModifiers());
// if (isTransientField)
// continue;
// fieldList.add(fields[i]);
// }
// System.out.println(clazz.getName());
// }
}
所需jar包
org.jumpmind.symmetric
symmetric-csv
3.5.19