今天又學(xué)了一招,jsp轉(zhuǎn)換成Excel.
在Web應(yīng)用中,很多數(shù)據(jù)經(jīng)常要導(dǎo)出成Excel文檔。用專門的生成真正的Excel文檔的方式比較復(fù)雜,不太好用。所以經(jīng)常用一種簡單的方式來實(shí)現(xiàn),即將報(bào)表保存為HTML格式,然后用Excel打開。
實(shí)現(xiàn)方式:
第一步,用JSP實(shí)現(xiàn)HTML版本的報(bào)表
第二步,在該JSP頁面頭部設(shè)置response的ContentType為Excel格式
<% response.setContentType("application/vnd.ms-excel;charset=GBK"); %>
中文問題:
查看源代碼時(shí)發(fā)現(xiàn)JSP文件中寫死的中文為亂碼,則在JSP文件頭部添加一行
<%@ page contentType="text/html; charset=gb2312" %>
查看源代碼時(shí)發(fā)現(xiàn)文字為中文,但是用Excel打開為亂碼則在<html>與<head>中加入
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
用Servlet實(shí)現(xiàn)也是類似的處理方法。
實(shí)現(xiàn)樣例:Test.jsp
<%@ page contentType="text/html; charset=GBK" %>
<% response.setContentType("application/vnd.ms-excel;charset=GBK"); %>
<HTML>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<head><title>Test</title></head>
<body>
<TABLE borderColor=#111111 cellSpacing=0 cellPadding=2 width=1200 align=center border=1>
<TR>
<TD align=center width="10%" height=20 rowSpan=2>項(xiàng)目 </TD>
<TD align=center width="2%" height=20 rowSpan=2>計(jì)量單位 </TD>
<TD align=center width="4%" height=20>滿期賠付率 </TD>
</TR>
</TABLE>
</body>
</HTML>