C # Implements 20 lines of code online preview documents (word, excel, pdf, txt, png) based on NPOI+Office COM component

Because of the need of the project, we need an online preview of office function. The editorial started with the method provided by Microsoft, which is simple and fast, but does not meet the development needs of the editorial.

Another way is to convert the file into an html file and preview the html file. Small partners interested in Microsoft's approach can take a look. It's simple and straightforward enough: word+excle+pdf form online browsing

Let's talk about the method used in the small edition. This preview method is based on the open source NPOI+Office COM components. These dynamic link libraries need to be introduced in the use. The general situation is as follows:

C# Online Preview Documents (word, excel, pdf, txt, png)

  1. Preview mode: convert files into html files and preview html files
  2. Preview word file: You need to introduce Interop.Microsoft.Office.Interop.Word.dll (Office COM + component)
  3. Preview Excel file: You need to introduce Interop.Microsoft.Office.Interop.Excel.dll (Office COM + component)
  4. PDF files are directly embedded in browsers for viewing without conversion (pdf reader needs to be installed) (access files directly using the path)
  5. Text files are embedded directly into the browser for viewing, without conversion (direct access to the file path can be used)
  6. Picture files are embedded directly into the browser for viewing, without conversion (direct access to the file path can be used)

 

The following edition will learn about preview word file and preview excel file.

Dead work:

1. Creating MVC project, introducing NPOI and office Com component dynamic link libraries, using VS2017 in the minor edition.

Introduce directly into NuGet (demonstrating only the introduction of NPOI, the same operation as the introduction of Interop.Microsoft.Office.Interop.Word and Interop.Microsoft.Office.Interop.Excel)

 

2. Create an excel file and word file under the Content file. The contents can be customized.

 

Coding:

Backend code:

When we are ready to finish, we begin to write code for debugging. The code is as follows. I paste it directly into the whole controller.

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#Online preview documents (word, excel, pdf, txt, png)
        //1,Preview: Converting files to html File then preview html file
        //2,preview word Document: Need to be introduced Interop.Microsoft.Office.Interop.Word.dll(Office COM Components)
        //3,preview Excel Document: Need to be introduced Interop.Microsoft.Office.Interop.Excel.dll(Office COM assembly) 
        //4,PDF Files are embedded directly into browsers for viewing without conversion (installation required) pdf Reader)
        //5,Text files are embedded directly into browsers for viewing without conversion
        //6,Picture files are embedded directly into browsers for viewing without conversion.


        #region Excel Preview method

        /// <summary>
        ///  excel Convert to html
        /// </summary>
        /// <param name="path">The path of the document to be converted</param>
        /// <param name="savePath">Converted html Storage Path</param>
        /// <param name="wordFileName">After conversion html Name of document</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 Preview method

        /// <summary>
        ///  word Convert to html
        /// </summary>
        /// <param name="path">The path of the document to be converted</param>
        /// <param name="savePath">Converted html Storage Path</param>
        /// <param name="wordFileName">After conversion html Name of document</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; }
        }
    }
}

Front-end code:

The code is as follows. I paste the whole page directly.

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

<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
   
    //preview excel
    function ExcelToHtml() {
        $.ajax({
            url: "/Home/ExcelToHtml",
            data: "",
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                //Get the vertical position of the window
                var iWidth = 1400;
                var iHeight = 800;
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //Get the horizontal position of the window
                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');

               
            }
        });
    }

    //preview word
    function WordToHtml() {
        $.ajax({
            url: "/Home/WordToHtml",
            data: "",
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                //Get the vertical position of the window
                var iWidth = 1400;
                var iHeight = 800;
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //Get the horizontal position of the window
                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="preview excel" />
       <input type="button" onclick="WordToHtml()" value="preview word" />
</div>

 

Effect View:

Online preview excel:

As follows, we clearly read the excel we prepared beforehand.

 

 

 

Online preview excel:

As follows, it is clear that we have read the word we prepared beforehand.

 

 

 

 

Summary:

Here's a simple online preview of office, which is an initial manuscript that needs to be optimized for subsequent functions.

Interested friends can pay attention to a wave. Next time we learn how to edit online, save in real time (save every change) and save by one click (save after editing).

The original address: https://www.cnblogs.com/xiongze520/p/11358585.html

Reprinted please indicate the source, thank you!

Keywords: C# Excel JSON JQuery Javascript

Added by Arab Prince on Thu, 15 Aug 2019 11:50:50 +0300