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

转载请注明出处,谢谢!

相关文章
|
2月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
101 10
|
3月前
|
安全 搜索推荐 iOS开发
WPS Office for Mac 7.3.1 - 写作、表格处理、PPT 制作和 PDF 编辑
WPS Office for Mac 7.3.1 - 写作、表格处理、PPT 制作和 PDF 编辑
159 8
WPS Office for Mac 7.3.1 - 写作、表格处理、PPT 制作和 PDF 编辑
|
8月前
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
555 5
|
5月前
|
文字识别 BI
【图片型PDF】批量识别扫描件PDF指定区域局部位置内容,将识别内容导出Excel表格或批量改名文件,基于阿里云OCR对图片型PDF识别改名案例实现
在医疗和政务等领域,图片型PDF文件(如病历、报告、公文扫描件)的处理需求广泛。通过OCR技术识别这些文件中的文字信息,提取关键内容并保存为表格,极大提高了信息管理和利用效率。本文介绍一款工具——咕嘎批量OCR系统,帮助用户快速处理图片型PDF文件,支持区域识别、内容提取、导出表格及批量改名等功能。下载工具后,按步骤选择处理模式、进行区域采样、批量处理文件,几分钟内即可高效完成数百个文件的处理。
555 8
|
7月前
|
人工智能 自然语言处理 JavaScript
Univer:开源全栈 AI 办公工具,支持 Word、Excel、PPT 等文档处理和多人实时协作
Univer 是一款开源的 AI 办公工具,支持 Word、Excel 等文档处理的全栈解决方案。它具有强大的功能、高度的可扩展性和跨平台兼容性,适用于个人和企业用户,能够显著提高工作效率。
763 9
Univer:开源全栈 AI 办公工具,支持 Word、Excel、PPT 等文档处理和多人实时协作
|
9月前
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
447 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
|
8月前
|
C#
【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)).
135 2
|
9月前
|
JSON 数据格式
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
LangChain-20 Document Loader 文件加载 加载MD DOCX EXCEL PPT PDF HTML JSON 等多种文件格式 后续可通过FAISS向量化 增强检索
644 2
|
11月前
内存或磁盘不足,excel无法再次打开或保存任何文档
内存或磁盘不足,excel无法再次打开或保存任何文档
242 2
|
11月前
【科研技巧】简单的在Office Word 2019中设置页脚的页码从指定页(正文)开始
如何在Microsoft Word 2019中设置页码从指定页面(通常是正文开始页)启动的方法。
271 2

热门文章

最新文章