java web Excel在网页预览
程序员文章站
2022-07-13 15:23:04
...
导入jar包:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.9</version>
</dependency>
后台处理方法代码:
/**
* @param response
* @param wb excel生成的Workbook (根据业务创建Workbook)
* @throws IOException
*/
public void writToAjax(HttpServletResponse response, HSSFWorkbook wb) throws IOException {
try {
ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
ethc.setOutputColumnHeaders(false);
ethc.setOutputRowNumbers(false);
ethc.processWorkbook(wb);
Document htmlDocument = ethc.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
out.close();
String htmlStr = new String(out.toByteArray(), "UTF-8");
htmlStr = htmlStr.replace("<h2>Sheet1</h2>", "").replace("<h2>Sheet2</h2>", "")
.replace("<h2>Sheet3</h2>", "").replace("<h2>Sheet4</h2>", "").replace("<h2>Sheet5</h2>", "");
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.print(htmlStr);
pw.flush();
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
前端请求:
<script>
$('#officeContent').attr("src","[请求路径]");
</script>
<html><body>
<iframe id="officeContent" src="" width=0 height=0 frameborder=0></iframe></body></html>
推荐阅读
-
Java 在Excel单元格中应用一种/多种字体样式
-
Java和PHP在Web开发方面对比分析
-
在ASP.NET MVC里对Web Page网页进行权限控制
-
Java在Excel中创建多级分组、折叠或展开分组的实现
-
Java和.Net版通用工具类实现--生成自定义Web Html/Excel测试用例和测试报告
-
Java Poi 在Excel中输出特殊符号
-
快速在Ubuntu服务器上部署java web项目
-
在新linux系统上部署Java web 项目服务器
-
Java自定义注解以及在POI导出EXCEL中的一个应用 javaannotationPOIexcel
-
java web Excel在网页预览