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

简介: 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

转载请注明出处,谢谢!

相关文章
|
SQL C# 数据库
EPPlus库的安装和使用 C# 中 Excel的导入和导出
本文介绍了如何使用EPPlus库在C#中实现Excel的导入和导出功能。首先,通过NuGet包管理器安装EPPlus库,然后提供了将DataGridView数据导出到Excel的步骤和代码示例,包括将DataGridView转换为DataTable和使用EPPlus将DataTable导出为Excel文件。接着,介绍了如何将Excel数据导入到数据库中,包括读取Excel文件、解析数据、执行SQL插入操作。
EPPlus库的安装和使用 C# 中 Excel的导入和导出
【Azure App Service】使用Microsoft.Office.Interop.Word来操作Word文档,部署到App Service后报错COMException
System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (0x80040154 (REGDB_E_CLASSNOTREG)).
284 2
|
文字识别 C# Python
使用C#将几个Excel文件合并去重分类
使用C#将几个Excel文件合并去重分类
214 3
|
数据库
C#Winform使用NPOI获取word中的数据
C#Winform使用NPOI获取word中的数据
410 2
|
C# 开发者 Windows
WPF遇上Office:一场关于Word与Excel自动化操作的技术盛宴,从环境搭建到代码实战,看WPF如何玩转文档处理的那些事儿
【8月更文挑战第31天】Windows Presentation Foundation (WPF) 是 .NET Framework 的重要组件,以其强大的图形界面和灵活的数据绑定功能著称。本文通过具体示例代码,介绍如何在 WPF 应用中实现 Word 和 Excel 文档的自动化操作,包括文档的读取、编辑和保存等。首先创建 WPF 项目并设计用户界面,然后在 `MainWindow.xaml.cs` 中编写逻辑代码,利用 `Microsoft.Office.Interop` 命名空间实现 Office 文档的自动化处理。文章还提供了注意事项,帮助开发者避免常见问题。
1088 0
|
开发框架 算法 .NET
C#使用MiniExcel导入导出数据到Excel/CSV文件
C#使用MiniExcel导入导出数据到Excel/CSV文件
560 0
|
5月前
|
XML 前端开发 C#
C#编程实践:解析HTML文档并执行元素匹配
通过上述步骤,可以在C#中有效地解析HTML文档并执行元素匹配。HtmlAgilityPack提供了一个强大而灵活的工具集,可以处理各种HTML解析任务。
278 19
|
6月前
|
监控 算法 C#
C#与Halcon联合编程实现鼠标控制图像缩放、拖动及ROI绘制
C#与Halcon联合编程实现鼠标控制图像缩放、拖动及ROI绘制
1031 0
|
C# 开发者
C# 一分钟浅谈:Code Contracts 与契约编程
【10月更文挑战第26天】本文介绍了 C# 中的 Code Contracts,这是一个强大的工具,用于通过契约编程增强代码的健壮性和可维护性。文章从基本概念入手,详细讲解了前置条件、后置条件和对象不变量的使用方法,并通过具体代码示例进行了说明。同时,文章还探讨了常见的问题和易错点,如忘记启用静态检查、过度依赖契约和性能影响,并提供了相应的解决建议。希望读者能通过本文更好地理解和应用 Code Contracts。
311 3
|
存储 安全 编译器
学懂C#编程:属性(Property)的概念定义及使用详解
通过深入理解和使用C#的属性,可以编写更清晰、简洁和高效的代码,为开发高质量的应用程序奠定基础。
1039 12