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

转载请注明出处,谢谢!

相关文章
|
3月前
|
存储
Vue3 实现 PDF 文件在线预览功能
Vue3 实现 PDF 文件在线预览功能
315 0
iframe 在线预览pdf、word、excel、ppt、txt、图片、视频
iframe 在线预览pdf、word、excel、ppt、txt、图片、视频
|
3月前
|
Web App开发 JavaScript 前端开发
网页VUE纯前端在线预览编辑Office,支持doc/docx、xls/xlsx、ppt/pptx、pdf等格式
随着互联网技术的不断发展,越来越多的企业开始采用在线办公模式,微软Office Word 是最好用的文档编辑工具,然而doc、docx、xls、xlsx、ppt、pptx等格式的Office文档是无法直接在浏览器中直接打开的,如果可以实现Web在线预览编辑OffIce,肯定会还带来了更高效、便捷的办公体验,为我们的工作带来了更多可能性。
547 0
|
2月前
|
存储 Java Apache
Spring Boot整合OpenOffice实现Word、Excel、PPT在线预览
Spring Boot整合OpenOffice实现Word、Excel、PPT在线预览
140 0
|
1月前
|
存储 SQL C#
C#实现Excel合并单元格数据导入数据集
C#实现Excel合并单元格数据导入数据集
|
1月前
|
Web App开发 JavaScript 前端开发
2024年纯前端VUE在线编辑微软Office/金山WPS的Word/Excel文档
现在,随着数字化进程渗透到到各行各业,数据安全已经成为了数字化革命中的重要组成部分,而在线Office成在OA、ERP、文档系统中得到了广泛的应用,为我国的信息化事业也做出了巨大贡献。随着操作系统、浏览器及Office软件的不断升级和更新换代,加上国家对信息化、数字化系统要求的不断提升,一些厂家的WebOffice控件产品不断被淘汰出局,而现存的几个产品也存在以下几个问题:
422 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转换中文乱码问题处理
105 0
|
3月前
|
开发框架 .NET C#
无标题自用临时文档.C# | python交互
无标题自用临时文档.C# | python交互
93 0
|
3月前
|
Python
Python办公自动化【Excel查询重复数据、Excel提取身份证号信息、Python操作Excel模块库文档、Python操作Word基础 】(四)-全面详解(学习总结---从入门到深化)
Python办公自动化【Excel查询重复数据、Excel提取身份证号信息、Python操作Excel模块库文档、Python操作Word基础 】(四)-全面详解(学习总结---从入门到深化)
43 0
|
4月前
|
Windows
Windows 10 Word Excel PPT文件打开速度缓慢解决办法
Windows 10 Word Excel PPT文件打开速度缓慢解决办法

热门文章

最新文章