用Java进行EXCEL导出导入用POI,但在此项目中要进行CSV导出,翻阅网上资料 现把自己实例写出,以供自己以后
可能用上.
首先 CSV格式 就是字符串中间加逗号(,)然后拼成字符串输出。
public StringBuffer getCSVString(StringBuffer sb,List<MarketQuotationInfo> marketInfoList)
{
StringBuffer sbuffer = new StringBuffer(sb);
if(marketInfoList!=null&&marketInfoList.size()>0)
{
int k=marketInfoList.size();
for(int i=0;i<k;i++)
{
MarketQuotationInfo mff = (MarketQuotationInfo)marketInfoList.get(i);
sbuffer.append(""+ new SimpleDateFormat("yyyy-MM- dd").format(mff.getOccurTime()).toString()+","
+new SimpleDateFormat("HH:mm:ss").format(mff.getOccurTime())+","
+mff.getCommodityId()+","
+mff.getPrice()+"\r");
}
}
return sbuffer;
}
其次:
MarketQuotationInfo 为页面显示列表对象.
再次..
public void download(HttpServletResponse response,StringBuffer sb) throws Exception
{
String fileName = "行情数据"+System.currentTimeMillis();
RequestUtils.setFileDownloadHeader(response, fileName+".csv");
response.setContentType("application/vnd.ms-csv;charset=gb2312");
PrintWriter pw = response.getWriter();
//pw.write(s);
pw.print(sb.toString());
pw.close();
}
返回头部处理:
public static void setFileDownloadHeader(HttpServletResponse response, String filename) {
String headerValue = "attachment;";
headerValue += " filename=\"" + encodeURIComponent(filename) +"\";";
headerValue += " filename*=utf-8''" + encodeURIComponent(filename);
response.setHeader("Content-Disposition", headerValue);
}
组装一下运行OK 导出CSV格式文档.