C# 基於NPOI+Office COM組件 實現20行程式碼在線預覽文檔(word,excel,pdf,txt,png)

  • 2019 年 10 月 3 日
  • 筆記

由於項目需要,需要一個在線預覽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

 轉載請註明出處,謝謝!