星期六, 三月 26, 2005

用JSP生成Excel文件下载的最简单的方法

Tips:没想到Excel可以直接打开用<table> HTML tag的文件,并且能正确显示颜色和字体等信息.

<%
String path=request.getRealPath("/");
StringBuffer outstr = new StringBuffer();
PrintWriter pout = response.getWriter();
response.setContentType("application/x-msexcel");
java.util.Calendar ca=java.util.Calendar.getInstance();
String filename=ca.getTime()+"_filename.xls";

response.setHeader("Content-Disposition","attachment; filename="+filename);
pout.println("");
StringBuffer _finalStr=new StringBuffer();
_finalStr.append("\n");
_finalStr.append("");
_finalStr.append("
工资计算
考勤开始时间"+termstartdate+"
结束时间:"+termenddate+"
工资计算时间:"+ca.getTime()+"
计算人Good
工号UserId\n
");
pout.print(_finalStr.toString());
pout.close();
outstr=null;
%>