Export JSP to Excel

Posted in :

這個功能滿實用的,而且出乎意料的簡單,因為匯出成 html,副檔案是 .xls ,用Excel 開啟也都正常。

JSP export as excel example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Export to Excel - Demo</title>
</head>
<body>
 <%
 String exportToExcel = request.getParameter("exportToExcel");
 if (exportToExcel != null
 && exportToExcel.toString().equalsIgnoreCase("YES")) {
 response.setContentType("application/vnd.ms-excel");
 response.setHeader("Content-Disposition", "inline; filename="
 + "excel.xls");
 
 }
 %>
 <table align="left" border="2">
 <thead>
 <tr bgcolor="lightgreen">
 <th>Sr. No.</th>
 <th>Text Data</th>
 <th>Number Data</th>
 </tr>
 </thead>
 <tbody>
 <%
 for (int i = 0; i < 10; i++) {
 %>
 <tr bgcolor="lightblue">
 <td align="center"><%=i + 1%></td>
 <td align="center">This is text data <%=i%></td>
 <td align="center"><%=i * i%></td>
 </tr>
 <%
 }
 %>
 </tbody>
 </table>
 <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> 
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <%
 if (exportToExcel == null) {
 %>
 <a href="excel.jsp?exportToExcel=YES">Export to Excel</a>
 <%
 }
 %>
</body>
</html>

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *