Word/Excel 在线预览

简介: 前言 近日项目中做到一个功能,需要上传附件后能够在线预览。之前也没做过这类似的,于是乎就查找了相关资料,.net实现Office文件预览大概有这几种方式:  ① 使用Microsoft的Office组件将文件直接转换为html文件(优点:代码实现最简单,工作强度最小。

前言

近日项目中做到一个功能,需要上传附件后能够在线预览。之前也没做过这类似的,于是乎就查找了相关资料,.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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>弹出层</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<style>
.black_overlay{
 display: none;
 position: absolute;
 top: 0%;
 left: 0%;
 width: 100%;
 height: 100%;
 background-color: black;
 z-index:1001;
 -moz-opacity: 0.8;
 opacity:.80;
 filter: alpha(opacity=80);
}
.white_content {
 display: none;
 position: absolute;
 top: 10%;
 left: 10%;
 width: 80%;
 height: 80%;
 border: 16px solid lightblue;
 background-color: white;
 z-index:1002;
 overflow: auto;
}
.white_content_small {
 display: none;
 position: absolute;
 top: 20%;
 left: 30%;
 width: 40%;
 height: 50%;
 border: 16px solid lightblue;
 background-color: white;
 z-index:1002;
 overflow: auto;
}
</style>
<script type="text/javascript">
//弹出隐藏层
function ShowDiv(show_div,bg_div){
 document.getElementById(show_div).style.display='block';
 document.getElementById(bg_div).style.display='block' ;
 var bgdiv = document.getElementById(bg_div);
 bgdiv.style.width = document.body.scrollWidth; 
 // bgdiv.style.height = $(document).height();
 $("#"+bg_div).height($(document).height());
};
//关闭弹出层
function CloseDiv(show_div,bg_div)
{
 document.getElementById(show_div).style.display='none';
 document.getElementById(bg_div).style.display='none';
};
</script>
</head>
<body>
<input id="Button1" type="button" value="点击弹出层" onclick="ShowDiv('MyDiv','fade')" />
<!--弹出层时背景层DIV-->
<div id="fade" class="black_overlay">
</div>
 <div id="MyDiv" class="white_content">
  <div style="text-align: right; cursor: default; height: 40px;">
   <span style="font-size: 16px;" onclick="CloseDiv('MyDiv','fade')">关闭</span>
  </div>
  目前来说,我还是喜欢这个自己改造的弹出层。自己在项目中也用的是这个。
 </div>
</body>
</html>
View Code

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

前台代码

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

后台方法

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

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

首先新建一个帮助类

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

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

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

    }
}
View Code

后台调用方法

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

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

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

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

 

如果小伙伴有更好得实现方式或者其他建议,欢迎留言告知~

 

  • 感谢你的阅读。如果你觉得这篇文章对你有帮助或者有启发,就请推荐一下吧~你的精神支持是博主强大的写作动力。欢迎转载!
  • 博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高(其实是个菜B),不足和错误之处在所难免,希望大家能够批评指出。
  • 欢迎加入.NET 从入门到精通技术讨论群→523490820 期待你的加入
  • 不舍得打乱,就永远学不会复原。被人嘲笑的梦想,才更有实现的价值。
  • 我的博客:http://www.cnblogs.com/zhangxiaoyong/
目录
相关文章
iframe 在线预览pdf、word、excel、ppt、txt、图片、视频
iframe 在线预览pdf、word、excel、ppt、txt、图片、视频
|
2月前
|
存储 Java Apache
Spring Boot整合OpenOffice实现Word、Excel、PPT在线预览
Spring Boot整合OpenOffice实现Word、Excel、PPT在线预览
133 0
|
1月前
|
Web App开发 JavaScript 前端开发
2024年纯前端VUE在线编辑微软Office/金山WPS的Word/Excel文档
现在,随着数字化进程渗透到到各行各业,数据安全已经成为了数字化革命中的重要组成部分,而在线Office成在OA、ERP、文档系统中得到了广泛的应用,为我国的信息化事业也做出了巨大贡献。随着操作系统、浏览器及Office软件的不断升级和更新换代,加上国家对信息化、数字化系统要求的不断提升,一些厂家的WebOffice控件产品不断被淘汰出局,而现存的几个产品也存在以下几个问题:
417 1
2024年纯前端VUE在线编辑微软Office/金山WPS的Word/Excel文档
|
2月前
|
Java Linux 数据安全/隐私保护
Java【代码 16】将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理
【2月更文挑战第3天】Java 将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理
101 0
|
3月前
|
Python
Python办公自动化【Excel查询重复数据、Excel提取身份证号信息、Python操作Excel模块库文档、Python操作Word基础 】(四)-全面详解(学习总结---从入门到深化)
Python办公自动化【Excel查询重复数据、Excel提取身份证号信息、Python操作Excel模块库文档、Python操作Word基础 】(四)-全面详解(学习总结---从入门到深化)
39 0
|
4月前
|
Windows
Windows 10 Word Excel PPT文件打开速度缓慢解决办法
Windows 10 Word Excel PPT文件打开速度缓慢解决办法
|
4月前
在word、ppt、excel编辑软件标题栏顶部左上角加入自定义功能:另存为、导出PDF
在word、ppt、excel编辑软件标题栏顶部左上角加入自定义功能:另存为、导出PDF
|
5月前
|
XML 测试技术 数据格式
推荐一个跨平台支持Word, Excel, CSV, Email等30多种格式的操作库
推荐一个跨平台支持Word, Excel, CSV, Email等30多种格式的操作库
32 0
|
5月前
|
XML JSON 开发框架
盘点5个C#实用的Word、PPT、Excel、Mail第三方库
盘点5个C#实用的Word、PPT、Excel、Mail第三方库
84 0
|
23天前
|
SQL 缓存 easyexcel
面试官问10W 行级别数据的 Excel 导入如何10秒处理
面试官问10W 行级别数据的 Excel 导入如何10秒处理
51 0