引言

之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询。

方案一

直接在浏览器中打开Office文档在页面上的链接。会弹出如下窗口:

优点:主流浏览器都支持。

缺点:Office文档链接在浏览器中打开,会有如上图的提示,需用户自己选择打开或者保存功能,如果客户电脑上安装迅雷下载软件,会启动迅雷下载,用户体验不好。

方案二

office文档转html,首先引入com组件中office库,然后在程序集扩展中引入word,excel,ppt的dll。

然后F6生成,会报如下错误:

解决办法:

office文档转换html辅助类:

Office2HtmlHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
namespace Wolfy.OfficePreview
{public class Office2HtmlHelper{/// <summary>/// Word转成Html/// </summary>/// <param name="path">要转换的文档的路径</param>/// <param name="savePath">转换成html的保存路径</param>/// <param name="wordFileName">转换成html的文件名字</param>public static void Word2Html(string path, string savePath, string wordFileName){Word.ApplicationClass word = new Word.ApplicationClass();Type wordType = word.GetType();Word.Documents docs = word.Documents;Type docsType = docs.GetType();Word.Document doc = (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, Word.WdSaveFormat.wdFormatFilteredHTML });docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);}/// <summary>/// Excel转成Html/// </summary>/// <param name="path">要转换的文档的路径</param>/// <param name="savePath">转换成html的保存路径</param>/// <param name="wordFileName">转换成html的文件名字</param>public static void Excel2Html(string path, string savePath, string wordFileName){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";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();}/// <summary>/// ppt转成Html/// </summary>/// <param name="path">要转换的文档的路径</param>/// <param name="savePath">转换成html的保存路径</param>/// <param name="wordFileName">转换成html的文件名字</param>public static void PPT2Html(string path, string savePath, string wordFileName){Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();string strSourceFile = path;string strDestinationFile = savePath + wordFileName + ".html";Microsoft.Office.Interop.PowerPoint.Presentation prsPres = ppApp.Presentations.Open(strSourceFile, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);prsPres.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);prsPres.Close();ppApp.Quit();}}
}

Office2Html.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Office2Html.aspx.cs" Inherits="Wolfy.OfficePreview.Office2Html" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title>
</head>
<body><form id="form1" runat="server"><div><asp:Button Text="Word转Html" ID="btnWord" runat="server" CommandArgument="docx" OnClick="btnWord_Click" /><asp:Button ID="btnExcel" Text="Excel转Html" runat="server" CommandArgument="xlsx" OnClick="btnWord_Click" /><asp:Button ID="btnPPT" Text="PPT转Html" runat="server" CommandArgument="ppt" OnClick="btnWord_Click" /></div></form>
</body>
</html>

Office2Html.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace Wolfy.OfficePreview
{public partial class Office2Html : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void btnWord_Click(object sender, EventArgs e){Button btn = sender as Button;switch (btn.CommandArgument){case "docx":Office2HtmlHelper.Word2Html(MapPath("/Doc/分析某网站的SEO策略(外链篇).doc"), MapPath("/Html/"), "分析某网站的SEO策略(外链篇)");break;case "xlsx":Office2HtmlHelper.Excel2Html(MapPath("/Excel/1994-2013北京市历年最低工资标准.xlsx"), MapPath("/Html/"), "1994-2013北京市历年最低工资标准");break;case "ppt":Office2HtmlHelper.PPT2Html(MapPath("/PPT/23种设计模式详解.ppt"), MapPath("/Html/"), "23种设计模式详解");break;default:break;}}}
}

测试结果:

这里为了测试特找了含有图片的office文档,浏览正常:

要求:机器需安装office,并且office环境是纯净的,所谓纯净就是不能有多个版本,lz曾经在电脑上安装过wps,被害苦了总是报如下错误:

报这个错误,只能哭了,网上的关于00046的解决办法都尝试了,不行。然后不得不重新安装office,然后笑了。最好安装office完整版,因为原来装的不是完整版,不知道有没有这方面的原因,也没有测试,建议完整版。

方案三

office文档转PDF,PDF转swf,使用flexpaper+swftools实现在线浏览。

在操作office2007时,需安装SaveAsPDFandXPS.exe ,安装成功后,如图所示:

只有安装了SaveAsPDFandXPS.exe,程序操作office文档,才有office文档另存为pdf文件。office2010不需要安装了,内置有这个功能。

核心代码:

Office2PDFHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
namespace Wolfy.OfficePreview
{/// <summary>/// Office2Pdf 将Office文档转化为pdf/// </summary>public class Office2PDFHelper{public Office2PDFHelper(){//// TODO: 在此处添加构造函数逻辑//}/// <summary>/// Word转换成pdf/// </summary>/// <param name="sourcePath">源文件路径</param>/// <param name="targetPath">目标文件路径</param>/// <returns>true=转换成功</returns>public static bool DOCConvertToPDF(string sourcePath, string targetPath){bool result = false;Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;object paramMissing = Type.Missing;Word.ApplicationClass wordApplication = new Word.ApplicationClass();Word.Document wordDocument = null;try{object paramSourceDocPath = sourcePath;string paramExportFilePath = targetPath;Word.WdExportFormat paramExportFormat = exportFormat;bool paramOpenAfterExport = false;Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;int paramStartPage = 0;int paramEndPage = 0;Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;bool paramIncludeDocProps = true;bool paramKeepIRM = true;Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;bool paramDocStructureTags = true;bool paramBitmapMissingFonts = true;bool paramUseISO19005_1 = false;wordDocument = wordApplication.Documents.Open(ref paramSourceDocPath, ref paramMissing, ref paramMissing,ref paramMissing, ref paramMissing, ref paramMissing,ref paramMissing, ref paramMissing, ref paramMissing,ref paramMissing, ref paramMissing, ref paramMissing,ref paramMissing, ref paramMissing, ref paramMissing,ref paramMissing);if (wordDocument != null)wordDocument.ExportAsFixedFormat(paramExportFilePath,paramExportFormat, paramOpenAfterExport,paramExportOptimizeFor, paramExportRange, paramStartPage,paramEndPage, paramExportItem, paramIncludeDocProps,paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,paramBitmapMissingFonts, paramUseISO19005_1,ref paramMissing);result = true;}catch{result = false;}finally{if (wordDocument != null){wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);wordDocument = null;}if (wordApplication != null){wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);wordApplication = null;}GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();GC.WaitForPendingFinalizers();}return result;}/// <summary>/// 把Excel文件转换成PDF格式文件  /// </summary>/// <param name="sourcePath">源文件路径</param>/// <param name="targetPath">目标文件路径</param>/// <returns>true=转换成功</returns>public static bool XLSConvertToPDF(string sourcePath, string targetPath){bool result = false;Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;object missing = Type.Missing;Excel.ApplicationClass application = null;Excel.Workbook workBook = null;try{application = new Excel.ApplicationClass();object target = targetPath;object type = targetType;workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing);workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);result = true;}catch{result = false;}finally{if (workBook != null){workBook.Close(true, missing, missing);workBook = null;}if (application != null){application.Quit();application = null;}GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();GC.WaitForPendingFinalizers();}return result;}///<summary>        /// 把PowerPoint文件转换成PDF格式文件       ///</summary>        ///<param name="sourcePath">源文件路径</param>     ///<param name="targetPath">目标文件路径</param> ///<returns>true=转换成功</returns> public static bool PPTConvertToPDF(string sourcePath, string targetPath){bool result;PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;object missing = Type.Missing;PowerPoint.ApplicationClass application = null;PowerPoint.Presentation persentation = null;try{application = new PowerPoint.ApplicationClass();persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);result = true;}catch{result = false;}finally{if (persentation != null){persentation.Close();persentation = null;}if (application != null){application.Quit();application = null;}GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();GC.WaitForPendingFinalizers();}return result;}}
}

Office2PDF.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Office2PDF.aspx.cs" Inherits="Wolfy.OfficePreview.Office2PDF" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title>
</head>
<body><form id="form1" runat="server"><div><asp:Button Text="Word转PDF" ID="btnWord" runat="server" CommandArgument="docx" OnClick="btnWord_Click" /><asp:Button ID="btnExcel" Text="Excel转PDF" runat="server" CommandArgument="xlsx" OnClick="btnWord_Click" /><asp:Button ID="btnPPT" Text="PPT转PDF" runat="server" CommandArgument="ppt" OnClick="btnWord_Click" /></div></form>
</body>
</html>

Office2PDF.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace Wolfy.OfficePreview
{public partial class Office2PDF : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void btnWord_Click(object sender, EventArgs e){Button btn = sender as Button;switch (btn.CommandArgument){case "docx":Office2PDFHelper.DOCConvertToPDF(MapPath("/Doc/分析某网站的SEO策略(外链篇).doc"), MapPath("/PDF/分析某网站的SEO策略(外链篇).pdf"));break;case "xlsx":Office2PDFHelper.XLSConvertToPDF(MapPath("/Excel/1994-2013北京市历年最低工资标准.xlsx"), MapPath("/PDF/1994-2013北京市历年最低工资标准.pdf"));break;case "ppt":Office2PDFHelper.PPTConvertToPDF(MapPath("/PPT/23种设计模式详解.ppt"), MapPath("/PDF/23种设计模式详解.pdf"));break;default:break;}}}
}

测试结果:

此方案office转pdf文件的过程的要求与方案二要求相同。

pdf转换完成后,就可以将pdf转换为swf,使用flexpaper+swftools实现在线浏览了,可参考我之前的一篇文章:

FlexPaper+SWFTool+操作类=在线预览PDF

方案四

office文档直接转换为swf,使用flexpaper+swftool实现在先浏览。

office直接转换为swf,这里使用flashpaper来实现:

FlashPaper是一个虚拟打印机,可将word文件直接转化成swf格式文件(.doc.xls .txt .pdf等文件都可以正常生成SWF格式)。

这里只贴出核心代码:

Office2Swf.aspx.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace Wolfy.OfficePreview
{public partial class Office2Swf : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void btnWord_Click(object sender, EventArgs e){Button btn = sender as Button;switch (btn.CommandArgument){case "docx":ConvertOffice2Swf(MapPath("/Doc/分析某网站的SEO策略(外链篇).doc"), MapPath("/SWF/分析某网站的SEO策略(外链篇).swf"));break;case "xlsx":Office2PDFHelper.XLSConvertToPDF(MapPath("/Excel/1994-2013北京市历年最低工资标准.xlsx"), MapPath("/SWF/1994-2013北京市历年最低工资标准.swf"));break;case "ppt":Office2PDFHelper.PPTConvertToPDF(MapPath("/PPT/23种设计模式详解.ppt"), MapPath("/SWF/23种设计模式详解.swf"));break;default:break;}}/// <summary>/// office 转swf/// </summary>/// <param name="officePath">要转换的office文档路径</param>/// <param name="swfPath">转换后swf的路径</param>private void ConvertOffice2Swf(string officePath, string swfPath){Process process = new Process();     //创建进程对象 ProcessStartInfo startInfo = new ProcessStartInfo();string paperroot = @"C:\Program Files\Macromedia\FlashPaper 2\FlashPrinter.exe";//这里是FlashPrinter的路径string docFile = officePath;string swfFile = swfPath;startInfo.FileName = paperroot;startInfo.Arguments = docFile + " -o " + swfFile;startInfo.UseShellExecute = false;     //不使用系统外壳程序启动 startInfo.RedirectStandardInput = false;   //不重定向输入 startInfo.RedirectStandardOutput = false;   //重定向输出 startInfo.CreateNoWindow = true;     //不创建窗口 process.StartInfo = startInfo;process.Start();   if (process != null)process.Close();}}
}

鉴于测试时,flashpaper在将office文档转换为swf的时候,在使用flexpaper的浏览时,出现转换的内容为空,猜测:flexpaper能打开的swf文件与flashpaper转的swf文件不兼容。最后使用flashpaper将office文档转换为pdf,然后走方案三,pdf转swf的步骤。另外本地测试时,没问题。将项目部署在IIS上,不能浏览,出现卡死的情况,调试发现,文件太大,在office还没完全转换为pdf的情况下,swftool工具就去寻找pdf文件,出现错误。

IIS上,无法浏览,查询网上解决方案,和权限这块有关,按照步骤设置了,未果,有点遗憾。

方案五

使用点聚公司的weboffice控件,测试后发现兼容性较差,放弃。有兴趣的可以研究一下。

方案六

office转pdf后,直接浏览器打开,此方案鉴于目前主流浏览器都集成adobe reader功能,可实现直接打开PDF文件。将pdf文件链接可直接打开。

必要条件:本地需安装adobe reader类似软件。

方案七

http://blogs.office.com/2013/04/10/office-web-viewer-view-office-documents-in-a-browser/

方案八

web在线打印,打印阅览,打印维护,打印设计

总结

鉴于项目情况选择一个适合的方案,其中有方案只是曲线救国,但是同样能达到要求。如果您觉得对你有所帮助,不妨推荐一下,让更多的人都能看到,谢谢你能看到文章最后。

demo:

链接:https://pan.baidu.com/s/1hqEpx5a 密码:gupg

参考文章:

http://www.cnblogs.com/expectszc/archive/2012/04/04/2432149.html

http://www.cnblogs.com/lexlin/articles/2478027.html

http://www.cnblogs.com/gossip/p/3473024.html

http://www.cnblogs.com/expectszc/archive/2012/04/04/2432149.html

  • 博客地址:http://www.cnblogs.com/wolf-sun/ 
    博客版权:如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。

阅读原文

asp.net实现word、excel、ppt、pdf在线预览相关推荐

  1. [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有真相,总有一款适合你!...

    [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有真相,总有一款适合你! 引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 ...

  2. C#编写ASP.NET Core的Web API并部署到IIS上的详细教程(API用于准确获取Word/Excel/PPT/PDF的页数)6 -将项目部署到IIS,及常见错误解决方案

    C#编写ASP.NET Core的Web API并部署到IIS上的详细教程(API用于准确获取Word/Excel/PPT/PDF的页数)6 -将项目部署到IIS,及常见错误解决方案 1.前言 2.安 ...

  3. ❤️强烈推荐!Word、Excel、PPT、PDF在线预览解决方案

    大家好,我是锋哥: 平时大伙开发项目的时候,经常遇到业务需求Word.Excel.PPT.PDF在线预览功能: 市面上这方面的解决方案也有一些,不做过多评价.今天主要推荐的是一个特定提前下的永久免费解 ...

  4. Java准确获取Word/Excel/PPT/PDF的页数(附Word页数读不准的处理办法)

    Java准确获取Word/Excel/PPT/PDF的页数(附Word页数读不准的处理办法) 1.需求背景 2.环境准备工作 2.1 JACOB介绍及安装 2.2 Microsoft Office W ...

  5. 前端ppt\word等等文件实现在线预览功能

    前端ppt\word等等文件实现在线预览功能 方法1:https://view.xdocin.com/view?src=你的文档地址 10天免费 方法2:https://view.officeapps ...

  6. 实现PPT的在线预览(动态,及转PDF)

    实现PPT的在线预览(动态,及转PDF) 公司的新需求,需要在网页上动态预览PPT,此处记录下,防止忘记. 之前在网上找了很多资料,比如:用POI 实现等,这里写下自己的实现方法 1.PPT 转PDF ...

  7. java实现word转pdf在线预览格式

    java实现word转pdf在线预览格式 前段时间的项目里涉及了此功能,调研过一些方案,踩过一些坑,一一总结在此. java转pdf的方案很多,但是很多都要收费,转pdf也有一些格式方面的问题. 方案 ...

  8. Java 实现word pdf在线预览

    Java 实现word pdf在线预览 最近项目有这个需求,查找了一些资料,在这整理一下. 首先,pdf的文件,浏览器本身支持预览,不需要做什么处理. controller: 简单说下思路:就是利用i ...

  9. Java实现PDF在线预览

    Java实现PDF在线预览 前言:之前一直PDF一直是下载后再查看,一直在想如何如何在线预览,现已找到方法,作此笔记,也希望都对其他人有所帮助 代码实现 @Slf4j @Controller @Req ...

  10. 搭建自己的pdf在线预览工具

    文章首发于我的个人博客 1.前言 ​ 在日常工作学习过程中,我们常常将自己的学习笔记和成果记录下来, 之后想通过网络将这些资料分享给其他人.如果你有个人博客,那么可以将你的总结用markdown写下来 ...

最新文章

  1. 大脑奖获得者Peter Dayan:生物决策机制为生存铺路,预编程是本能!
  2. Java数组的基本操作方法整理
  3. tinycore php,tinycore中文支持
  4. netmiko 记录日志_Pythonnetmiko模块的使用 | 学步园
  5. 《HTML与CSS入门经典(第8版)》——第2章 发布Web内容2.1 创建用于本章的示例文件...
  6. 把oracle卸载恢复,oracle干净卸载
  7. 如何使用STM32 HAL库驱动TFT-LCD实现手画板功能
  8. 数采仪厂家_环保数采仪生产厂家
  9. 《Real-Time Rendering 4th Edition》全文翻译 - 第7章 阴影(下)7.7 ~ 7.10
  10. 算法分析:大O符号/大Ω符号/大Θ符号/小o符号/小w符号
  11. Typora-PicGo-SMMS图床(Mac电脑和windows电脑)
  12. Scrapy框架整合英雄缩略图(APP)
  13. unity网络资源导入
  14. PointNet 翻译:
  15. Ardupilot姿态控制详解(完结篇)
  16. Linux内核之PCI设备
  17. 4周,从入门小白到爬虫老炮儿,薪资水平超过60% IT 新手!
  18. HTML Parser Jsoup - 网页抓取百度百科信息的例子
  19. firemonkey 点击任务栏图标不能最小化
  20. IEEE1588精密时钟(PTP网络时钟服务器)在数字化变电站时钟同步方面的应用

热门文章

  1. 音频(八)——C语言生成正弦波并用 I2S 输出
  2. 计算机班级的简介,简短的班级介绍,50字的班级简介
  3. 粽情端午动态PPT模板
  4. 监督学习、无监督学习和半监督学习区别
  5. Windows 应急响应篇(保姆级检查流程)
  6. python对接企业微信_Python对接企业微信会话内容存档功能的实践
  7. python爬虫爬取彩票中奖数字,简单计算概率并写入Excel文件中
  8. Android系统定制的导航侧边栏
  9. STM32 cudeIDE使用J-link下载程序
  10. APK安装失败的原因之一