这个很多网站都有,找了一个,感觉好用:
String queryResult = ...;
response.setContentType("application/csv");
response.setHeader("Content-Disposition", "inline; filename="result.csv"");
PrintWriter out = new PrintWriter(new OutputStreamWriter(
response.getOutputStream(), "UTF-8"));
out.print(queryResult);
out.close();
response.setContentType("application/csv");
response.setHeader("Content-Disposition", "inline; filename="result.csv"");
PrintWriter out = new PrintWriter(new OutputStreamWriter(
response.getOutputStream(), "UTF-8"));
out.print(queryResult);
out.close();
但我自己在做的时候遇到一个实际问题,因为我要导出的结果中有时间,它的格式是这样的2007-09-01 07:00:00,用notepad打开的话肯定没问题,但如果用excel打开就有点问题了,时间段会变成####,因为excel的时间格式是01/09/2007 07:00:00。所以要在导出前处理下这个string。
private static final DateFormat formatVLS = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private static final DateFormat formatCSV = new SimpleDateFormat("dd/MM/yyyy HH:mm");
private String convertTimeForCSV(String input) throws VLSException {
try {
return formatCSV.format(formatVLS.parse(input));
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new VLSException(VLSConstants.ERROR_FORMAT);
}
}
private static final DateFormat formatCSV = new SimpleDateFormat("dd/MM/yyyy HH:mm");
private String convertTimeForCSV(String input) throws VLSException {
try {
return formatCSV.format(formatVLS.parse(input));
} catch (ParseException e) {
// TODO Auto-generated catch block
throw new VLSException(VLSConstants.ERROR_FORMAT);
}
}