java实现excel、word在线预览

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("");
		/* 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('');	
			}
		});
		
		
		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;


/**
 * 
 * 〈一句话功能简述〉
* 〈功能详细描述〉 附件预览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(); } } } /** * * 功能描述:
* 〈功能详细描述〉图片预览 * * @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(); } } } /** * * 功能描述:
* 〈功能详细描述〉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)