首先jsp页面的一个按钮调用一个servlet,servlet所产生的数据,请求转发到一个jsp页面。
jsp页面的按钮调用一个servlet就不多说了。
下面是servlet代码。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
List list = (List) session.getAttribute("wagelist");
wageInfo wage = null;
StringBuffer tbody = new StringBuffer();//内容
StringBuffer thead = new StringBuffer();//打印出来的excel内容的头部
thead.append("<tr></tr>");
thead.append("<tr><td colspan='6' align='center'><strong>本月工资</strong></td></tr>");
thead.append("<thead><tr>");
thead.append("<td><strong>员工编号</strong></td>");
thead.append("<td><strong>员工姓名</strong></td>");
thead.append("<td><strong>应发工资</strong></td>");
thead.append("<td><strong>实发工资</strong></td>");
thead.append("<td><strong>保险扣除</strong></td>");
thead.append("<td><strong>补贴</strong></td>");
thead.append("</tr></thead>");
tbody.append("<tbody>");
//这里循环出来的数据自己给定。
for (int i = 0; i < list.size(); i++) {
wage = (wageInfo) list.get(i);
Double yingfa = wage.getWagebasic()+wage.getWagesubsidy();
Double shifa = wage.getWagebasic()+wage.getWagesubsidy()-wage.getGsbx()-wage.getNoworkbx()-wage.getOldbx();
Double baoxian = wage.getGsbx()+wage.getNoworkbx()+wage.getOldbx()+wage.getSybx()+wage.getYlbx();
tbody.append("<tr>");
tbody.append("<td>"+wage.getStaffid()+"</td>");
tbody.append("<td>"+wage.getStaffname()+"</td>");
tbody.append("<td>"+yingfa+"</td>");//应发工资
tbody.append("<td>"+shifa+"</td>");//实发工资
tbody.append("<td>"+baoxian+"</td>");//保险扣除
tbody.append("<td>"+wage.getWagesubsidy()+"</td>");//补贴
tbody.append("</tr>");
}
tbody.append("</tbody>");
String htmltable = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head>" +
"<table border=\"1\">"+thead+tbody+"</table>";
System.out.println(htmltable);
request.setAttribute("htmltable", htmltable);
request.getRequestDispatcher("exportExcel.jsp").forward(request, response);
}
jsp页面的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page contentType="application/msexcel;charset=utf-8"%>
<%
request.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition","attachment;filename=exportExcel.xls");//contentType=”application/vnd.ms-excel” 在浏览器中打开
String strd = (String)request.getAttribute("htmltable");
out.print(strd);
// 编码格式为utf-8
%>
需要注意的是:
servlet的字符集编码要和jsp页面的字符集编码要一致,不然导出的excel会出现乱码。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page contentType="application/msdoc;charset=utf-8"%>
<%
request.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition","attachment;filename=exportWord.doc");//contentType=”application/vnd.ms-excel” 在浏览器中打开
String strd = (String)request.getAttribute("htmltable");
out.print(strd);
// 编码格式为utf-8
%>
把jsp页面改为这样同样可以导出word文档。