前言

近日项目中做到一个功能,需要上传附件后能够在线预览。之前也没做过这类似的,于是乎就查找了相关资料,.net实现Office文件预览大概有这几种方式:

① 使用Microsoft的Office组件将文件直接转换为html文件(优点:代码实现最简单,工作强度最小。缺点:效果极差)

②使用Microsoft的Office组件将文件转换为PDF格式文件,然后再使用pdf2swf转换为swf文件,也就是flash文件在使用FlexPaper展示出来(优点:预览效果能接受,缺点:代码量大)

③使用Office online(优点:表现完美,缺点:不适合中小企业应用)

由于开发时间短而且还有其他功能点需要完成,所以暂时先已第一种方式实现了,这里也主要讲第一种方式,效果如下图:

具体实现

这里简单提一下效果图中的遮罩效果和上传实现,有喜欢的朋友也可以参考参考。

遮罩效果就是HTML+CSS+JS来实现的,全部代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"<br/>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><br/>
<html xmlns="http://www.w3.org/1999/xhtml"><br/>
<head><br/>
<title>弹出层</title><br/>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script><br/>
<style><br/>
.black_overlay{<br/>
 display: none;<br/>
 position: absolute;<br/>
 top: 0%;<br/>
 left: 0%;<br/>
 width: 100%;<br/>
 height: 100%;<br/>
 background-color: black;<br/>
 z-index:1001;<br/>
 -moz-opacity: 0.8;<br/>
 opacity:.80;<br/>
 filter: alpha(opacity=80);<br/>
}<br/>
.white_content {<br/>
 display: none;<br/>
 position: absolute;<br/>
 top: 10%;<br/>
 left: 10%;<br/>
 width: 80%;<br/>
 height: 80%;<br/>
 border: 16px solid lightblue;<br/>
 background-color: white;<br/>
 z-index:1002;<br/>
 overflow: auto;<br/>
}<br/>
.white_content_small {<br/>
 display: none;<br/>
 position: absolute;<br/>
 top: 20%;<br/>
 left: 30%;<br/>
 width: 40%;<br/>
 height: 50%;<br/>
 border: 16px solid lightblue;<br/>
 background-color: white;<br/>
 z-index:1002;<br/>
 overflow: auto;<br/>
}<br/>
</style><br/>
<script type="text/javascript"><br/>
//弹出隐藏层<br/>
function ShowDiv(show_div,bg_div){<br/>
 document.getElementById(show_div).style.display='block';<br/>
 document.getElementById(bg_div).style.display='block' ;<br/>
 var bgdiv = document.getElementById(bg_div);<br/>
 bgdiv.style.width = document.body.scrollWidth;<br/>
 // bgdiv.style.height = $(document).height();<br/>
 $("#"+bg_div).height($(document).height());<br/>
};<br/>
//关闭弹出层<br/>
function CloseDiv(show_div,bg_div)<br/>
{<br/>
 document.getElementById(show_div).style.display='none';<br/>
 document.getElementById(bg_div).style.display='none';<br/>
};<br/>
</script><br/>
</head><br/>
<body><br/>
<input id="Button1" type="button" value="点击弹出层" onclick="ShowDiv('MyDiv','fade')" /><br/>
<!--弹出层时背景层DIV--><br/>
<div id="fade" class="black_overlay"><br/>
</div><br/>
 <div id="MyDiv" class="white_content"><br/>
  <div style="text-align: right; cursor: default; height: 40px;"><br/>
   <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')">关闭</span><br/>
  </div><br/>
  目前来说,我还是喜欢这个自己改造的弹出层。自己在项目中也用的是这个。<br/>
 </div><br/>
</body><br/>
</html>

上传的话,因为文件比较小,所以采用的是保存在服务器,在数据库中存放路径的方式

前台代码

 <div class="white_content" id="MyDiv" style="text-align: center; display: none;"><br/>
            <div style="text-align: right; cursor: default; height: 40px;"><br/>
                <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')">关闭</span><br/>
            </div><br/>
            <tr style="width: 50%" id="upload_Image"><br/>
                <h1><br/>
                    请上传常见问题附件</h1><br/>
                <td align="right" class="Title"><br/>
                    上传附件<br/>
                </td><br/>
                <td><br/>
                    <asp:FileUpload ID="FileUpload1" runat="server" /><br/>
                    <asp:Label ID="label1" runat="server" ForeColor="Red"></asp:Label><br/>
                    <asp:Button ID="UploadButton" runat="server" Text="上传附件" OnClick="UploadButton_Click" /><br/>
                </td><br/>
            </tr><br/>
            <tr><br/>
                <td colspan="2" align="center" id="show_image" style="visibility: hidden"><br/>
                    <asp:Image ID="Image1" runat="server" Height="118px" Width="131px" /><br/>
                </td><br/>
            </tr><br/>
        </div>

后台方法

      try<br/>
            {<br/>
                string FullName = FileUpload1.PostedFile.FileName;//获取附件物理地址<br/>
                FileInfo fi = new FileInfo(FullName);<br/>
                string name = fi.Name;//获取附件名称<br/>
                string type = fi.Extension;//获取附件类型<br/>
                if (type == ".xls" || type == ".xlsx" || type == ".doc" || type == ".docx" || type == ".pdf")<br/>
                {<br/>
                    string SavePath = Server.MapPath("~\\uploadFile");//附件保存到文件夹下<br/>
                    if (!Directory.Exists(SavePath))<br/>
                    {<br/>
                        Directory.CreateDirectory(SavePath);<br/>
                    }<br/>
                    this.FileUpload1.PostedFile.SaveAs(SavePath + "\\" + name);//保存路径<br/>
                    #region 将附件内容保存到数据库中<br/>
                    int showsuccess = CMSModelManager.Submitted_questionsDAO.Save_File(name,type,SavePath);<br/>
                    if (showsuccess == )<br/>
                    {<br/>
                        this.label1.Text = "上传成功";<br/>
                    }<br/>
                    else<br/>
                    {<br/>
                        this.label1.Text = "服务器繁忙,请稍后重试";<br/>
                    }<br/>
                    #endregion<br/>
                }<br/>
                else<br/>
                {<br/>
                    this.label1.Text = "请选择正确的格式附件";<br/>
                }<br/>
            }<br/>
            catch (Exception ex)<br/>
            {<br/>
                Response.Write(ex.Message);<br/>
            }

图中所示的将Word转换成HTML的实现方式:

首先新建一个帮助类

using System;<br/>
using System.Collections.Generic;<br/>
using System.Web;<br/>
//using Microsoft.Office.Core;<br/>
using Word = Microsoft.Office.Interop.Word;

namespace Com.VanruPortal.Admin<br/>
{<br/>
    public class Office2HtmlHelper<br/>
    {<br/>
        /// <summary><br/>
        /// Word转成Html<br/>
        /// </summary><br/>
        /// <param name="path">要转换的文档的路径</param><br/>
        /// <param name="savePath">转换成html的保存路径</param><br/>
        /// <param name="wordFileName">转换成html的文件名字</param><br/>
        public static void Word2Html(string path, string savePath, string wordFileName)<br/>
        {

            Word.ApplicationClass word = new Word.ApplicationClass();<br/>
            Type wordType = word.GetType();<br/>
            Word.Documents docs = word.Documents;<br/>
            Type docsType = docs.GetType();<br/>
            Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true });<br/>
            Type docType = doc.GetType();<br/>
            string strSaveFileName = savePath + wordFileName + ".html";<br/>
            object saveFileName = (object)strSaveFileName;<br/>
            docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });<br/>
            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);<br/>
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);<br/>
        }<br/>
        /// <summary><br/>
        /// Excel转成Html<br/>
        /// </summary><br/>
        /// <param name="path">要转换的文档的路径</param><br/>
        /// <param name="savePath">转换成html的保存路径</param><br/>
        /// <param name="wordFileName">转换成html的文件名字</param><br/>
        public static void Excel2Html(string path, string savePath, string wordFileName)<br/>
        {<br/>
            string str = string.Empty;<br/>
            Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application();<br/>
            Microsoft.Office.Interop.Excel.Workbook workbook = null;<br/>
            Microsoft.Office.Interop.Excel.Worksheet worksheet = null;<br/>
            workbook = repExcel.Application.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);<br/>
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[];<br/>
            object htmlFile = savePath + wordFileName + ".html";<br/>
            object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;<br/>
            workbook.SaveAs(htmlFile, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);<br/>
            object osave = false;<br/>
            workbook.Close(osave, Type.Missing, Type.Missing);<br/>
            repExcel.Quit();<br/>
        }

    }<br/>
}

后台调用方法

            #region 上传成功后将文件转换<br/>
                        string physicalPath = Server.MapPath(Server.UrlDecode("/uploadFile"+"\\"+ name));//读取相对路径<br/>
                        string extension = Path.GetExtension(physicalPath);//获取后缀名

                        string[] show_name = name.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);//此处的name是上面上传附件中的名称分割<br/>
                        string show_name_View = show_name[];//拿到实际name<br/>
                        switch (extension)<br/>
                        {

                            case ".doc":<br/>
                            case ".docx":<br/>
                                Office2HtmlHelper.Word2Html(MapPath("/uploadFile" + "\\" + name + ""),<br/>
                                    MapPath("/Html/"), "" + show_name_View + "");//调用帮助类中生成WordHtml的方法,并保存起来<br/>
                                Response.Write("<script>window.open('/Html/" + show_name_View + ".html','_blank')</script>");//跳转并打开保存的相对路径中hmtl文件<br/>
                                break;<br/>
                            case ".xls":<br/>
                            case ".xlsx":<br/>
                                Office2HtmlHelper.Excel2Html(MapPath("/uploadFile" + "\\" + name + ""),<br/>
                                    MapPath("/Html/"), "" + show_name_View + "");<br/>
                                Response.Write("<script>window.open('/Html/" + show_name_View + ".html','_blank')</script>");<br/>
                                break;<br/>
                            default:<br/>
                                break;<br/>
                        }<br/>
                        #endregion

至此,一个简易的上传附件在线浏览已经全部实现