java实现excel、word在线预览

最近项目上有一个新的需求是实现附件的预览,支持word、excel、pdf等附件的在线预览,刚接到任务时一脸懵逼,以为直接访问本地的附件地址就可以,结果word、excel直接下载下来了,紧接着去百度各种搜集资料,发现jacob 这个jar包可以实现word、excel转换为pdf,在本地测试了半天这个jar包不支持jdk1.7,。而后咨询了一下同事,同事说可以直接以流的形式输出到页面,突发奇想值得尝试,结果成功了,好了不说了,上代码吧。

excel的jsp代码如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.uqiansoft.web.util.StringUtils" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";String declareno = StringUtils.convertNulltoString(request.getAttribute("declareno"));
String selectId = StringUtils.convertNulltoString(request.getAttribute("selectId"));
%>
<!DOCTYPE html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html><head><base href="<%=basePath%>"><title>打开文档</title><link rel="stylesheet" type="text/css" href="<%=basePath%>style/reset.css"><link rel="stylesheet" type="text/css" href="<%=basePath%>style/tab.css"><link rel="stylesheet" type="text/css" href="<%=basePath%>style/receive/content.css"><%@include file="../common.jsp"%><link rel="stylesheet" type="text/css" href="<%=basePath%>style/attachement.css" media="screen" /><script type="text/javascript" >function openDocument(url){var netOfficeEdit = document.getElementById("riseOffice");netOfficeEdit.OpenFromURL(url,"","Word.Document");//写入书签/* var unit = document.getElementById("danwei").value;var item = document.getElementById("shixiang").value;netOfficeEdit.SetbookmarkValue('danwei',unit);netOfficeEdit.SetbookmarkValue('shixiang',item);*/}function save(){var netOfficeEdit = document.getElementById("riseOffice");if (netOfficeEdit === null || netOfficeEdit === "undefined") { return false; }try {netOfficeEdit.SaveToURL("<%=basePath%>word/insertform?declareno=<%=StringUtils.escapeHTML(declareno, true, true) %>","editfile","","<%=basePath%>word/fawen.doc","form1");}catch (err) {alert("err:" + err.number + ":" + err.description);} finally { }}$(function(){var bodyheight = document.documentElement.clientHeight||document.body.clientHeight;$("#riseOffice").height(bodyheight);if(<%=StringUtils.escapeHTML(selectId, true, true) %> == 1){openDocument("<%=basePath%>word/fawen.doc");}else if (<%=StringUtils.escapeHTML(selectId, true, true) %> == 2){openDocument("<%=basePath%>word/fawenb.doc");}else if (<%=StringUtils.escapeHTML(selectId, true, true) %> == 3){openDocument("<%=basePath%>word/fawenN.doc");}var netOfficeEdit = document.getElementById("riseOffice");netOfficeEdit.FileNew = false;netOfficeEdit.FileOpen = false;netOfficeEdit.attachEvent("OnFileCommand",function(cmd,canceled){if(cmd == 3){save();}document.getElementById("riseOffice").CancelLastCommand = true;});});</script></head><body style="overflow: hidden;"><object id="riseOffice" classid="clsid:A39F1330-3322-4a1d-9BF0-0BA2BB90E970" codeBase="<%=basePath%>ocx/OfficeControl.cab#version=5,0,1,8" width="100%"><param name="BorderStyle" value="0"><param name="BorderColor" value="14402205"><param name="TitlebarColor" value="53668"><param name="TitlebarTextColor" value="0"><param name="MenubarColor" value="13160660"><param name="Caption" value="欢迎使用!"><param name="Titlebar" value="0"><param name="MaxUploadSize" value="10000000"><param name="CustomMenuCaption" value="辅助选项"><param name="ProductCaption" value="北京市经济信息中心"><param name="ProductKey" value="3B4C6C82E57D04EF01F5B34A84EFC65FEBC645CA"><SPAN STYLE="color:red">不能装载文档控件。请在检查浏览器的选项中检查浏览器的安全设置。</SPAN></object></body>
</html>

word的jsp代码如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="com.uqiansoft.web.util.StringUtils" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
pageContext.setAttribute("ctx", path);
%>
<!DOCTYPE html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html><head><base href="<%=basePath%>"><meta http-equiv="X-UA-Compatible" content="IE=10" /><title>打开文档模板</title><link rel="stylesheet" type="text/css" href="<%=basePath%>style/reset.css"><link rel="stylesheet" type="text/css" href="<%=basePath%>style/tab.css"><link rel="stylesheet" type="text/css" href="<%=basePath%>style/receive/content.css"><%-- <%@include file="../common.jsp"%> --%><link rel="stylesheet" type="text/css" href="<%=basePath%>style/attachement.css" media="screen" /><link rel="stylesheet" type="text/css" href="<%=basePath%>style/table.css"><script type="text/javascript" src="<%=basePath%>js/jquery.js"></script><script type="text/javascript" >var cmnPath = "<%=basePath%>";var path = "${path}";$(function(){var bodyheight = document.documentElement.clientHeight||document.body.clientHeight;$("#riseOffice").height(bodyheight-30);var url = cmnPath+"office/openWord?path="+encodeURI(encodeURI(path));openDocument(url);var netOfficeEdit = document.getElementById("riseOffice");netOfficeEdit.FileNew = false;netOfficeEdit.FileOpen = false;netOfficeEdit.FileSaveAs = true;//netOfficeEdit.FileSave = false;//是否可编辑参数netOfficeEdit.attachEvent("OnFileCommand",function(cmd,canceled){});});function openDocument(url){var readonly = false;var netOfficeEdit = document.getElementById("riseOffice");netOfficeEdit.OpenFromURL(url,readonly,"Word.Document");}</script></head><body style="overflow: hidden;"><object id="riseOffice" classid="clsid:A39F1330-3322-4a1d-9BF0-0BA2BB90E970" codeBase="<%=basePath%>ocx/OfficeControl.cab#version=5,0,1,8" width="100%"><param name="BorderStyle" value="0"><param name="BorderColor" value="14402205"><param name="TitlebarColor" value="53668"><param name="TitlebarTextColor" value="0"><param name="MenubarColor" value="13160660"><param name="Caption" value="欢迎使用!"><param name="Titlebar" value="0"><param name="MaxUploadSize" value="10000000"><param name="CustomMenuCaption" value="辅助选项"><param name="ProductCaption" value="北京市经济信息中心"><param name="ProductKey" value="3B4C6C82E57D04EF01F5B34A84EFC65FEBC645CA"><SPAN STYLE="color:red">不能装载文档控件。请在检查浏览器的选项中检查浏览器的安全设置。</SPAN></object></body>
</html>

pdf的jsp代码如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page import="com.tri.user.model.*"%>
<%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";request.setAttribute("basePath", basePath);
%>
<!DOCTYPE html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>在线预览</title>
<script type="text/javascript" src="<%=basePath%>js/jquery.js"></script>
<script type="text/javascript">var path = "${path}";$(function() {var cmnPath = "<%=basePath%>";var frame = document.getElementById("pdfIframe");path = cmnPath + "office/openPdf?path=" + encodeURI(encodeURI(path));$("#pdfContent").append("<iframe style='height:640px;width:100%;' src='"+path+"'></iframe>");/* alert(path);frame.src = path;frame.contentWindow.location.reload(true); */});
</script>
<style>
html,body {height: 100%;
}
</style>
</head>
<body><span id="pdfContent"> <!-- <iframe id="pdfIframe" style="height:640px;width:100%;"></iframe>  --></span>
</body>
</html>

图片文本的jsp如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="com.uqiansoft.web.util.StringUtils"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
pageContext.setAttribute("ctx", path);
%>
<!DOCTYPE html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>在线预览</title>
<%@include file="../common.jsp"%>
<link rel="stylesheet" type="text/css" href="<%=basePath%>js/magnify/jquery.magnify.min.css" media="screen" /><script type="text/javascript" src="<%=basePath%>js/jquery.js"></script>
<%-- <script type="text/javascript" src="<%=basePath%>js/jQueryRotate.js"></script>--%><script type="text/javascript" src="<%=basePath%>js/magnify/jquery.magnify.js"></script>
<script type="text/javascript">var cmnPath = "<%=basePath%>";var path = "${path}";var type = "${type}";$(function(){var frame = document.getElementById("mutationImage");if (type=="image") {$("#image_div").show();frame.src = cmnPath+"office/openImage?path="+encodeURI(encodeURI(path));} else {$("#txtContent").show();$("#txtContent").empty();url = cmnPath+"office/openOtherTxt?path="+encodeURI(encodeURI(path));$("#txtContent").append('<iframe style="height:600px;width:100%;" src="'+url+'"></iframe>');   }});function showImage() {var img_url = cmnPath+"office/openImage?path="+encodeURI(encodeURI(path));document.getElementById("data_href").href = img_url;}</script>
</head>
<body><span style="display: none;" width="100%;" height="100%;" id="txtContent"></span><div class="image-set" style="margin-top: 80px;margin: 80px;display: none;" align="center" id="image_div" ><a data-magnify="gallery" id="data_href" href="" onclick="showImage()" data-caption="图片预览" ><img width="500;" style="text-align: center;" id="mutationImage"  src="" alt=""></a></div>
</body>
</html>

java后端代码如下

package com.uqiansoft.web.controller.word;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import com.uqiansoft.annotation.SystemLog;/*** * 〈一句话功能简述〉<br> * 〈功能详细描述〉 附件预览Controller** @author songjinlong* @see [相关类/方法](可选)* @since [产品/模块版本] (可选)*/
@Controller
public class OfficeController {/*** 模拟访问* @param request* @return* @throws IOException*/@RequestMapping("/office/open")public String openOffice(HttpServletRequest request) throws IOException{String type = request.getParameter("type");String path = request.getParameter("path");if ("jpg".equalsIgnoreCase(type) || "bmp".equalsIgnoreCase(type)|| "png".equalsIgnoreCase(type)|| "jpeg".equalsIgnoreCase(type)) {//图片type = "image";} else if ("txt".equalsIgnoreCase(type)) {//txt文本type = "txt";} path = URLDecoder.decode(path,"UTF-8");request.setAttribute("path", path);request.setAttribute("type", type);if("doc".equalsIgnoreCase(type) || "docx".equalsIgnoreCase(type)) {return "word/wordView.jsp";} else if ("xlsx".equalsIgnoreCase(type) || "xls".equalsIgnoreCase(type)) {return "word/excelView.jsp";} else if ("pdf".equalsIgnoreCase(type)){return "word/pdfView.jsp";} else {return "word/ortherView.jsp";}}/*** excel文件页面显示* @param req* @param res* @throws Exception*/@RequestMapping("/office/openExcel")@SystemLog( model = "",description="")public void openExcel(HttpServletRequest request,HttpServletResponse res)throws Exception{String path = request.getParameter("path");path = URLDecoder.decode(path,"UTF-8");byte[] bdata = fileToBytes(path);if(bdata!=null){ServletOutputStream op;try {op = res.getOutputStream();op.write(bdata);op.close();if (op.equals(null)) {res.flushBuffer();}} catch (IOException e1) {e1.printStackTrace();}}}/*** word文件页面显示* @param req* @param res* @throws Exception*/@RequestMapping("/office/openWord")@SystemLog( model = "",description="")public void openWord(HttpServletRequest request,HttpServletResponse res)throws Exception{String path = request.getParameter("path");path = URLDecoder.decode(path,"UTF-8");byte[] bdata = fileToBytes(path);if(bdata!=null){ServletOutputStream op;try {op = res.getOutputStream();op.write(bdata);op.close();if (op.equals(null)) {res.flushBuffer();}} catch (IOException e1) {e1.printStackTrace();}}}/*** * 功能描述: <br>* 〈功能详细描述〉图片预览** @param request* @param res* @throws Exception* @see [相关类/方法](可选)* @since [产品/模块版本](可选)*/@RequestMapping("/office/openImage")@SystemLog( model = "",description="")public void openImage(HttpServletRequest request,HttpServletResponse res)throws Exception{String path = request.getParameter("path");path = URLDecoder.decode(path,"UTF-8");res.setHeader("Content-Disposition", "filename=" + "image");res.setContentType("image/*");byte[] bdata = fileToBytes(path);if(bdata!=null){ServletOutputStream op;try {op = res.getOutputStream();op.write(bdata);op.close();if (op.equals(null)) {res.flushBuffer();}} catch (IOException e1) {e1.printStackTrace();}}}/*** * 功能描述: <br>* 〈功能详细描述〉txt文本预览** @param request* @param res* @throws Exception* @see [相关类/方法](可选)* @since [产品/模块版本](可选)*/@RequestMapping("/office/openOtherTxt")@SystemLog( model = "",description="")public void openOtherTxt(HttpServletRequest request,HttpServletResponse res)throws Exception{String path = request.getParameter("path");path = URLDecoder.decode(path,"UTF-8");byte[] bdata = fileToBytes(path);res.reset();//res.setCharacterEncoding("UTF-8");res.setContentType("text/plain;charset=gb2312");if(bdata!=null){OutputStream op;try {op = res.getOutputStream();op.write(bdata);op.close();if (op.equals(null)) {res.flushBuffer();}} catch (IOException e1) {e1.printStackTrace();}}}/*** 返回服务端PDF文件流* @param request* @param response* @param user* @throws ServletException* @throws IOException*/@RequestMapping("/office/openPdf")public void getPdfFile(HttpServletRequest request, HttpServletResponse response) throws IOException {String path = request.getParameter("path");path = URLDecoder.decode(path,"UTF-8");response.reset();response.setContentType("application/pdf;charset=UTF-8");// 定义输出类型byte[] bdata = fileToBytes(path);if(bdata!=null){ServletOutputStream op;try {op = response.getOutputStream();op.write(bdata);op.close();if (op.equals(null)) {response.flushBuffer();}} catch (IOException e1) {e1.printStackTrace();}}}/*** @param path* @return*/@SuppressWarnings("resource")private byte[] fileToBytes(String path){byte[] buffer = null;File file = new File(path);FileInputStream fis = null;ByteArrayOutputStream bos = null;try {fis = new FileInputStream(file);bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1) {bos.write(b, 0, n);}buffer = bos.toByteArray();} catch (FileNotFoundException ex) {ex.printStackTrace();} catch (IOException e) {e.printStackTrace();}return buffer;}
}

java实现excel、word在线预览相关推荐

  1. 前端如何实现 Word 在线预览

    前端如何实现 Word 在线预览 在前端实现 Word 文件在线预览时,常用的方法包括使用第三方库.浏览器插件.后端服务器.在线文档转换平台等,具体如下: 使用第三方库 常见的前端第三方库包括 Mam ...

  2. office在线预览 word在线预览 .net在线预览 文件在线浏览接口

    office在线预览 word在线预览 excel在线预览 文件浏览接口服务 支持移动端浏览,只要能使用浏览器上网都可以使用,不需要安装任何第三方工具. 1.word在线预览 excel在线预览,.n ...

  3. php excel文件在线预览(走过的坑)

    php excel文件在线预览(走过的坑) 1.已经布好的服务如微软的Office365等平台服务 2.通过phpExcel扩展进行excel文件解析直接输出html 3通过openoffice进行文 ...

  4. word,excel,ppt在线预览功能

    我们在开发web项目时,尤其类似oa功能时总会遇到上传附件并在线预览的功能,发现一款api比较好使,下面简单介绍一下. 首先我利用自己的阿里云简单做了一个在线预览的demo,地址:http://app ...

  5. java word在线预览_java实现word转pdf在线预览(前端使用PDF.js;后端使用openoffice、aspose)...

    背景 之前一直是用户点击下载word文件到本地,然后使用office或者wps打开.需求优化,要实现可以直接在线预览,无需下载到本地然后再打开. 随后开始上网找资料,网上资料一大堆,方案也各有不同,大 ...

  6. 实现word在线预览 有php的写法 也有插件似

    1 <?php2 //header("Content-type:text/html;charset=utf-8");3 //word转html 展示4 $lj=$_GET[' ...

  7. spring boot2.X word在线预览 pdf.js

    最近公司项目需求需要在线预览word文档,并且不能在在线下载和编辑.在此记录我是如何做的. 针对word的在线预览网上大多给的解决方案就是先把word文件转成pdf,然后通过pdf.js在线预览pdf ...

  8. Java使用OpenOffice实现在线预览

    公司业务:在线预览office文件,调研了一下,目前市场上免费的,比较合适的,也就是OpenOffice了,事已至此,干活... 思路: 1.利用 OpenOffice 以及 jodconverter ...

  9. java用openOffice实现在线预览

    1. 原理 将 office 文档转换为 pdf ,返回文件流给前端实现预览. 当前的主浏览器都支持直接打开pdf文件,从而实现文件预览.如果是其他格式文件则得下载,因此用openOffice实现文件 ...

  10. Java实现文档在线预览

    欢迎大家关注我的公众号[老周聊架构],Java后端主流技术栈的原理.源码分析.架构以及各种互联网高并发.高性能.高可用的解决方案. 主要思路 使用openoffice方式实现word预览 安装open ...

最新文章

  1. 超牛EXCEL操作技巧,用的好,会涨工资哦
  2. 一文快速入门分库分表中间件 Sharding-JDBC (必修课)
  3. Linux/Centos7系统管理之进程与计划任务管理
  4. 高可用性的HDFS—Hadoop分布式文件系统深度实践
  5. 谁考了第k名(信息学奥赛一本通-T1176)
  6. 收藏 | 使用 YOLO及OpenCV 实现目标检测
  7. html常用的符号实体
  8. GSM:联通项目中的常见术语(BTS、BSC、MSC、VLR、HLR)
  9. 以太网最小帧长与TCP/IP的联合运用
  10. onfling滑动界面进行Activity切换
  11. ProGuard:保留包名,混淆类
  12. CSS定位设置实例——盒子的定位
  13. MongoDB学习(黑马教程)-3-数据库MongoDB的删除文档操作
  14. java 中文乱码转换_java中文乱码怎么转换
  15. 字模提取软件的使用(pctolCD2002,基于FPGA的VGA显示汉字)
  16. 在Hive中使用过的函数记录(百分比、截取字符串、分组TOP N、日期转换、日期是第几周)
  17. 微信语音amr文件转mp3
  18. STM32串口通信代码、ASCII码、XU4串口通信,printf只会转换为无符号类型,linux下的串口通信程序
  19. php 执行opcode,PHP编译原理之Opcode ( Operation Code ) PHP代码执行过程
  20. 机电设备如何有效监控?手把手教你最实用的

热门文章

  1. 超市管理系统软件测试用例图,超市管理系统用户管理模块测试用例集.doc
  2. mtk现在不支持语言的字库和输入法,支持的字库和输入法
  3. android系统输入法下载官网下载地址,kazakhsha kirgizwshi下载
  4. WES7创建系统恢复盘
  5. 经验分享——家校互动系统功能教程资源
  6. 01--QT GUI视频教程
  7. 音乐外链转换工具 php,音乐外链生成工具V2.1 支持14个音乐网站外链提取转换
  8. 线性代数辅导讲义(第五章 特征值特征向量)
  9. MATLAB矩阵转置
  10. [JS]回调函数例子