C# 基于NPOI+Office COM组件 实现20行代码在线预览文档(word,excel,pdf,txt,png)

由于项目需要,需要一个在线预览office的功能,小编一开始使用的是微软提供的方法,简单快捷,但是不符合小编开发需求,

就另外用了:将文件转换成html文件然后预览html文件的方法。对微软提供的方法感兴趣的小伙伴可以去看一下,够简单直接:word+excle+pdf表格在线浏览

我们来说一下小编使用的方法,这种预览方式基于开源的NPOI+Office COM组件,使用是需要引入这几个动态链接库,总体如下:


C#在线预览文档(word,excel,pdf,txt,png)

  1. 预览方式:将文件转换成html文件然后预览html文件
  2. 预览word文件:需要引入Interop.Microsoft.Office.Interop.Word.dll(Office COM+组件)
  3. 预览Excel文件:需要引入Interop.Microsoft.Office.Interop.Excel.dll(Office COM+组件)
  4. PDF文件直接嵌入到浏览器中进行查看,无需转换(需安装pdf阅读器)(直接使用文件的路径访问即可)
  5. 文本文件直接嵌入到浏览器进行查看,无需转换(直接使用文件的路径访问即可)
  6. 图片文件直接嵌入到浏览器进行查看,无需转换(直接使用文件的路径访问即可)

 

下面小编就预览word文件和预览excel文件进行学习一下。

准备工作:

1、创建MVC项目,引入NPOI和office Com组件动态链接库,小编使用的是VS2017,

  直接在NuGet里面引入(只演示NPOI的引入,Interop.Microsoft.Office.Interop.Word和Interop.Microsoft.Office.Interop.Excel的引入一样的操作)

 

2、在Content文件加下面建立一个excel文件和word文件,里面的内容可以自定义


 

 代码编写:

  后端代码:

   我们准备完成后就开始编写代码进行调试,代码如下,我直接整个控制器粘贴出来。

using Microsoft.Office.Interop.Excel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebOnlineWord.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        //C#在线预览文档(word,excel,pdf,txt,png)
        //1、预览方式:将文件转换成html文件然后预览html文件
        //2、预览word文件:需要引入Interop.Microsoft.Office.Interop.Word.dll(Office COM组件)
        //3、预览Excel文件:需要引入Interop.Microsoft.Office.Interop.Excel.dll(Office COM组件) 
        //4、PDF文件直接嵌入到浏览器中进行查看,无需转换(需安装pdf阅读器)
        //5、文本文件直接嵌入到浏览器进行查看,无需转换
        //6、图片文件直接嵌入到浏览器进行查看,无需转换


        #region Excel预览方法

        /// <summary>
        ///  excel 转换为html
        /// </summary>
        /// <param name="path">要转换的文档的路径</param>
        /// <param name="savePath">转换成的html的保存路径</param>
        /// <param name="wordFileName">转换后html文件的名字</param>
        public JsonResult ExcelToHtml()
        {
            ResultJson result = new ResultJson();
            string path = Server.MapPath("/Content/excel.xlsx");  
            string savePath = Server.MapPath("/Content/"); 
            string wordFileName = "ExcelToHtml";
            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";
            string resultUrl = htmlFile.ToString();
            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();
            result.str = "/Content/" + wordFileName + ".html"; ;
            return Json(result, JsonRequestBehavior.AllowGet);

        }

        #endregion


        #region Excel预览方法

        /// <summary>
        ///  word 转换为html
        /// </summary>
        /// <param name="path">要转换的文档的路径</param>
        /// <param name="savePath">转换成的html的保存路径</param>
        /// <param name="wordFileName">转换后html文件的名字</param>
        public JsonResult WordToHtml()
        {
            ResultJson result = new ResultJson();
            string path = Server.MapPath("/Content/word.docx");
            string savePath = Server.MapPath("/Content/");
            string wordFileName = "WordToHtml";
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Type wordType = word.GetType();
            Microsoft.Office.Interop.Word.Documents docs = word.Documents;
            Type docsType = docs.GetType();
            Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.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, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });
            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
            result.str = "/Content/" + wordFileName + ".html"; ;
            return Json(result, JsonRequestBehavior.AllowGet);

        }

        #endregion

        public class ResultJson
        {
            public bool res { get; set; }
            public string info { get; set; }
            public string str { get; set; }
        }
    }
}

 前端代码:

   代码如下,我直接整个页面粘贴出来。

@{
    ViewBag.Title = "Home Page";
}

<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
   
    //预览excel
    function ExcelToHtml() {
        $.ajax({
            url: "/Home/ExcelToHtml",
            data: "",
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                //获得窗口的垂直位置
                var iWidth = 1400;
                var iHeight = 800;
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //获得窗口的水平位置
                var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
                window.open(data.str, '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');

               
            }
        });
    }

    //预览word
    function WordToHtml() {
        $.ajax({
            url: "/Home/WordToHtml",
            data: "",
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                //获得窗口的垂直位置
                var iWidth = 1400;
                var iHeight = 800;
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //获得窗口的水平位置
                var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
                window.open(data.str, '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');


            }
        });
    }

</script>


<div style="margin-top:20px;height:800px">
      <input type="button" onclick="ExcelToHtml()" value="预览excel" />
       <input type="button" onclick="WordToHtml()" value="预览word" />
</div>

 


 效果查看:

  在线预览excel:

     如下,很显然读取到了我们事先准备好的excel。

 

 

 

  在线预览excel:

     如下,很显然读取到了我们事先准备好的word。

 

 


 

 

 总结:

 到这里一个简单的在线预览office就完成了,这是一个初始手稿,需要优化后续功能。

 感兴趣的朋友可以关注一波,我们下次学习怎么在线编辑,实时保存(每改一下保存一下)和一键保存(编辑完成后点击保存)

 原文地址:https://www.cnblogs.com/xiongze520/p/11358585.html

 转载请注明出处,谢谢!

 

欢迎关注订阅我的微信公众平台【熊泽有话说】,更多好玩易学知识等你来取
作者:熊泽-学习中的苦与乐
公众号:熊泽有话说
出处:https://www.cnblogs.com/xiongze520/p/11358585.html
创作不易,任何人或团体、机构全部转载或者部分转载、摘录,请在文章明显位置注明作者和原文链接。  

 

posted @ 2019-08-15 16:08  熊泽-学习中的苦与乐  阅读(9306)  评论(32编辑  收藏  举报