jsp导出Excel的核心部分代码是:
response.setContentType("application/msexcel");
response.setHeader("Content-Disposition", "inline;
filename="+new String("员工基本信息表.xls".getBytes("gb2312"), "ISO8859-1"));
1、效果图
导出到Excel
2、源代码部分
1)VO部分
public class UserVO {
private String id;
private String name;
private int age;
private String address;
public UserVO(){};
public UserVO(String id, String name, int age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
}
2)列表list部分
<%@ page language="java" import="java.util.*,vo.UserVO" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
table{
border: solid 1px #B4B4B4;
border-collapse: collapse; --折叠样式.
}
tr th{
background:url("../../images/gray/bg_table_th.gif") repeat;
padding-left:4px;
height:27px;
border: solid 1px #B4B4B4;
}
tr td{
height:25px;
padding:4px;
border: solid 1px #B4B4B4;
}
id | name | Age | Address |
<%=tl.getId() %> | <%=tl.getName() %> | <%=tl.getAge() %> | <%=tl.getAddress() %> |
3)导出部分
<%@ page language="java" import="java.util.*,vo.UserVO" pageEncoding="UTF-8" contentType="application/msexcel" %>
<%
response.setContentType("application/msexcel");
response.setHeader("Content-Disposition", "inline; filename="+new String("员工基本信息表.xls".getBytes("gb2312"), "ISO8859-1"));
%>
table, th, td {
border: 1px solid #000;
}
td {
text-align: center;
vertical-align: middle;
}
/*为了解决导出身份证时候,显示科学记数形式*/
td {
mso-number-format: '\@';
}
id | name | Age | Address |
<%=tl.getId() %> | <%=tl.getName() %> | <%=tl.getAge() %> | <%=tl.getAddress() %> |
4)Servlet控制部分
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List
for(int i=0;i<15;i++){
list.add( new UserVO("00"+i, "gaojigsong", i, "广东深圳"+i));
}
String type = request.getParameter("type");
if("list".equals(type)){
//list
System.out.println(list);
request.setAttribute("list", list);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}else{
//export
request.setAttribute("list", list);
request.getRequestDispatcher("/export.jsp").forward(request, response);
}
}