引言

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

方案一

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

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

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

方案二

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

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

解决办法:

office文档转换html辅助类:

 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[];
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();
}
}
}

Office2HtmlHelper

 <%@ 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

 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不需要安装了,内置有这个功能。

核心代码:

 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 = ;
int paramEndPage = ;
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;
}
}
}

Office2PDFHelper

 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;
}
}
}
}

Office2PDF

 <%@ 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

测试结果:

此方案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格式)。

这里只贴出核心代码:

 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

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

  1. [Asp.net]常见word,excel,ppt,pdf在线预览方案(转)

    引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 直接在浏览器中打开Office文档在页面上的链接.会弹出如下窗口: 优点:主流浏览器都支持. 缺点: ...

  2. 转载: Asp.net常见word,excel,ppt,pdf在线预览方案

    参考链接: http://www.cnblogs.com/wolf-sun/p/3569960.html

  3. uploadify 下载组件使用技巧和在线预览 word,excel,ppt,pdf的方案

    http://www.cnblogs.com/wolf-sun/p/3565184.html uploadify 上传工具的使用技巧 http://www.cnblogs.com/wolf-sun/p ...

  4. Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结

    Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结 1. office word  excel pdf 的web预览要求 ...

  5. 在线文档转换API word,excel,ppt等在线文件转pdf、png

    在线文档转换API提供word,excel,ppt等在线文件转pdf.png等,文档:https://www.juhe.cn/docs/api/id/259 接口地址:http://v.juhe.cn ...

  6. Aspose office (Excel,Word,PPT),PDF 在线预览

    前文: 做个备份,拿的是试用版的 Aspose,功能见标题 代码: /// <summary> /// Aspose office (Excel,Word,PPT),PDF 在线预览 // ...

  7. 微信小程序云开发-云存储-下载并打开文件文件(word/excel/ppt/pdf)

    一.wxml文件 1.写文本框,用来获取文件链接. 2.按钮,点击下载文件 <!-- 下载文件(word/excel/ppt/pdf等) --> <view class=" ...

  8. 微信小程序云开发-云存储-上传文件(word/excel/ppt/pdf)到云存储

    说明 word/excel/ppt/pdf是从客户端会话选择文件.使用chooseMessageFile中选择文件. 一.wxml文件 上传按钮,绑定chooseFile <!--上传文件(wo ...

  9. asp.net word ecxel类型文件在线预览

    asp.net word ecxel类型文件在线预览 首先得引用COM: Microsoft Excel 10 Object Library Microsoft Word 10 Object Libr ...

随机推荐

  1. Git命令

    1. 检出项目到本地 git clone git@github.com:michaelliao/gitskills.git 2. 查看当前工作区状态 git status 3. 添加文件或文件夹至版本 ...

  2. docker 基础使用

    搜索某个镜像: docker  search  busybox 拉取: docker  pull  busybox 查看: docker  images 启动并运行: docker run -it b ...

  3. Python测试函数的方法之一

    Python测试函数的方法之一 首先介绍简单的try......except尝试运行的放例如下面的图和代码来简单介绍下: 注释:提醒以下代码环境为2.7.x 请3.x以上的同学们老规矩print(把打 ...

  4. EZchip将推全球首款100核64位ARM A-53芯片

    EZchip将推全球首款100核64位ARM A-53芯片 2015-02-25 16:32:03   来源:互联网    关键字: 将推  全球  64位  arm EZchip日前表示,将准备开发 ...

  5. UNITY自带的PACKAGE的UTILITY 里面有一个自带的FPS COUNTER

    UNITY自带的PACKAGE的UTILITY 里面有一个自带的FPS COUNTER 可用,但是脚本是保密的?

  6. [No000096]程序员面试题集【上】

    对几家的面试题凭记忆做个总结,基本全部拿到offer,由于时间比较长,题目只写大体意思,然后给出自己当时的答案(不保证一定正确): abstract类不可以被实例化 蛋糕算法: 平面分割空间:(n-1 ...

  7. 详解用CSS3制作圆形滚动进度条动画效果

    主  题 今天手把手教大家用CSS3制作圆形滚动进度条动画,想不会都难!那么,到底是什么东东呢?先不急,之前我分享了一个css实现进度条效果的博客<CSS实现进度条和订单进度条>,但是呢, ...

  8. play with usb

    1) struct usbdevfs_bulktransfer {        unsigned int ep;        unsigned int len;        unsigned i ...

  9. 当AngularJS POST方法碰上PHP

    问题描述 怎么POST过去给PHP都收不到资料? $_POST方法取不到正确的传入值! 原理说明 AngularJS这套framework使用的AJAX方法中,资料传递的格式为JSON,送出去的hea ...

  10. JavaScript OOP 之「创建对象」

    工厂模式 工厂模式是软件工程领域一种广为人知的设计模式,这种模式抽象了创建具体对象的过程.工厂模式虽然解决了创建多个相似对象的问题,但却没有解决对象识别的问题. function createPers ...