当前位置: 移动技术网 > IT编程>开发语言>c# > C# 基于NPOI+Office COM组件 实现20行代码在线预览文档(word,excel,pdf,txt,png)

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

2019年08月15日  | 移动技术网IT编程  | 我要评论
由于项目需要,需要一个在线预览office的功能,小编一开始使用的是微软提供的方法,简单快捷,但是不符合小编开发需求, 就另外用了:将文件转换成html文件然后预览html文件的方法。对微软提供的方法感兴趣的小伙伴可以去看一下,够简单直接:word+excle+pdf表格在线浏览 我们来说一下小编使 ...

由于项目需要,需要一个在线预览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就完成了,这是一个初始手稿,需要优化后续功能。

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

 原文地址:

 转载请注明出处,谢谢!

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网