由于项目需要, 需要一个在线预览 Office 的功能, 小编一开始使用的是微软提供的方法, 简单快捷, 但是不符合小编开发需求,
就另外用了: 将文件转换成 html 文件然后预览 HTML 文件的方法. 对微软提供的方法感兴趣的小伙伴可以去看一下, 够简单直接: Word+excle+PDF 表格在线浏览
我们来说一下小编使用的方法, 这种预览方式基于开源的 NPOI+Office COM 组件, 使用是需要引入这几个动态链接库, 总体如下:
C# 在线预览文档(Word,Excel,PDF,txt,PNG)
预览方式: 将文件转换成 HTML 文件然后预览 HTML 文件
预览 Word 文件: 需要引入 Interop.Microsoft.Office.Interop.Word.dll(Office COM + 组件)
预览 Excel 文件: 需要引入 Interop.Microsoft.Office.Interop.Excel.dll(Office COM + 组件)
PDF 文件直接嵌入到浏览器中进行查看, 无需转换(需安装 PDF 阅读器)(直接使用文件的路径访问即可)
文本文件直接嵌入到浏览器进行查看, 无需转换(直接使用文件的路径访问即可)
图片文件直接嵌入到浏览器进行查看, 无需转换(直接使用文件的路径访问即可)
下面小编就预览 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 = (Windows.screen.availHeight - 30 - iHeight) / 2;
- // 获得窗口的水平位置
- var iLeft = (Windows.screen.availWidth - 10 - iWidth) / 2;
- Windows.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 = (Windows.screen.availHeight - 30 - iHeight) / 2;
- // 获得窗口的水平位置
- var iLeft = (Windows.screen.availWidth - 10 - iWidth) / 2;
- Windows.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