最近 看到很多人要将网页保存成word格式,
所以就试了下使用POI来讲网页保存成word
基本思路就是在网页提交时,把整个页面的源文件提交到后台,然后写入word中
下面是一个简单的示例,可以参考下
首先看JSP页面,像下面这样
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>jsp转word</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<img alt="ss" src="0.jpg">
<table border="1" width="80%">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>0</td>
</tr>
</table>
<p>
这是个测试页面,用来把jsp页面转换成word
</p>
<div style="color: red;">
红色的字呀
</div>
<div style="width: 100px;height: 100px;background-color: yellow;">
黄色的背景呀
</div>
<form action="servlet/exportServlet" method="post">
<input type="hidden" name="html"/>
<input type="button" οnclick="saveAsWord()" value="保存">
</form>
</body>
<script type="text/javascript">
function saveAsWord(){
var f = document.forms[0];
f.html.value = document.documentElement.innerHTML;
f.submit();
}
</script>
</html>
这样页面的效果如下
看下serlvet的代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
request.setAttribute("text", "request");
String html = request.getParameter("html");
if(html != null){
byte[] bs = html.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(bs);
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
FileOutputStream ostream = new FileOutputStream("D:\\word.doc");
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
}
request.getRequestDispatcher("/index.jsp").include(request, response);
}
打开生成的word会看到下面这么
点击确定,就看到生成的文件啦
示例仅供参考!