[Asp.net]常見word,excel,ppt,pdf在線預覽方案,有圖有真相,總有一款適合你!

引言

以前項目須要,查找了office文檔在線預覽的解決方案,順便記錄一下,方便之後查詢。html

方案一

直接在瀏覽器中打開Office文檔在頁面上的連接。會彈出以下窗口:web

 

優勢:主流瀏覽器都支持。設計模式

缺點:Office文檔連接在瀏覽器中打開,會有如上圖的提示,需用戶本身選擇打開或者保存功能,若是客戶電腦上安裝迅雷下載軟件,會啓動迅雷下載,用戶體驗很差。瀏覽器

方案二

office文檔轉html,首先引入com組件中office庫,而後在程序集擴展中引入word,excel,ppt的dll。app

 

而後F6生成,會報以下錯誤:ide

解決辦法:函數

office文檔轉換html輔助類:工具

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Microsoft.Office.Core;
 6 using Word = Microsoft.Office.Interop.Word;
 7 namespace Wolfy.OfficePreview
 8 {
 9     public class Office2HtmlHelper
10     {
11         /// <summary>
12         /// Word轉成Html
13         /// </summary>
14         /// <param name="path">要轉換的文檔的路徑</param>
15         /// <param name="savePath">轉換成html的保存路徑</param>
16         /// <param name="wordFileName">轉換成html的文件名字</param>
17         public static void Word2Html(string path, string savePath, string wordFileName)
18         {
19 
20             Word.ApplicationClass word = new Word.ApplicationClass();
21             Type wordType = word.GetType();
22             Word.Documents docs = word.Documents;
23             Type docsType = docs.GetType();
24             Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)path, true, true });
25             Type docType = doc.GetType();
26             string strSaveFileName = savePath + wordFileName + ".html";
27             object saveFileName = (object)strSaveFileName;
28             docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });
29             docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
30             wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
31 
32         }
33         /// <summary>
34         /// Excel轉成Html
35         /// </summary>
36         /// <param name="path">要轉換的文檔的路徑</param>
37         /// <param name="savePath">轉換成html的保存路徑</param>
38         /// <param name="wordFileName">轉換成html的文件名字</param>
39         public static void Excel2Html(string path, string savePath, string wordFileName)
40         {
41             string str = string.Empty;
42             Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application();
43             Microsoft.Office.Interop.Excel.Workbook workbook = null;
44             Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
45             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);
46             worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
47             object htmlFile = savePath + wordFileName + ".html";
48             object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
49             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);
50             object osave = false;
51             workbook.Close(osave, Type.Missing, Type.Missing);
52             repExcel.Quit();
53         }
54         /// <summary>
55         /// ppt轉成Html
56         /// </summary>
57         /// <param name="path">要轉換的文檔的路徑</param>
58         /// <param name="savePath">轉換成html的保存路徑</param>
59         /// <param name="wordFileName">轉換成html的文件名字</param>
60         public static void PPT2Html(string path, string savePath, string wordFileName)
61         {
62             Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();
63             string strSourceFile = path;
64             string strDestinationFile = savePath + wordFileName + ".html";
65             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);
66 
67             prsPres.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue);
68             prsPres.Close();
69             ppApp.Quit();
70         }
71     }
72 }
Office2HtmlHelper
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Office2Html.aspx.cs" Inherits="Wolfy.OfficePreview.Office2Html" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 8     <title></title>
 9 </head>
10 <body>
11     <form id="form1" runat="server">
12         <div>
13             <asp:Button Text="Word轉Html" ID="btnWord" runat="server" CommandArgument="docx" OnClick="btnWord_Click" />
14             <asp:Button ID="btnExcel" Text="Excel轉Html" runat="server" CommandArgument="xlsx" OnClick="btnWord_Click" />
15             <asp:Button ID="btnPPT" Text="PPT轉Html" runat="server" CommandArgument="ppt" OnClick="btnWord_Click" />
16         </div>
17     </form>
18 </body>
19 </html>
Office2Html.aspx
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 namespace Wolfy.OfficePreview
 9 {
10     public partial class Office2Html : System.Web.UI.Page
11     {
12         protected void Page_Load(object sender, EventArgs e)
13         {
14 
15         }
16         protected void btnWord_Click(object sender, EventArgs e)
17         {
18             Button btn = sender as Button;
19             switch (btn.CommandArgument)
20             {
21                 case "docx":
22                     Office2HtmlHelper.Word2Html(MapPath("/Doc/分析某網站的SEO策略(外鏈篇).doc"), MapPath("/Html/"), "分析某網站的SEO策略(外鏈篇)");
23                     break;
24                 case "xlsx":
25                     Office2HtmlHelper.Excel2Html(MapPath("/Excel/1994-2013北京市歷年最低工資標準.xlsx"), MapPath("/Html/"), "1994-2013北京市歷年最低工資標準");
26                     break;
27                 case "ppt":
28                     Office2HtmlHelper.PPT2Html(MapPath("/PPT/23種設計模式詳解.ppt"), MapPath("/Html/"), "23種設計模式詳解");
29                     break;
30                 default:
31                     break;
32             }
33         }
34     }

35 }

測試結果:
post

這裏爲了測試特找了含有圖片的office文檔,瀏覽正常:測試

 要求:機器需安裝office,而且office環境是純淨的,所謂純淨就是不能有多個版本,lz曾經在電腦上安裝過wps,被害苦了老是報以下錯誤:

報這個錯誤,只能哭了,網上的關於00046的解決辦法都嘗試了,不行。而後不得不從新安裝office,而後笑了。最好安裝office完整版,由於原來裝的不是完整版,不知道有沒有這方面的緣由,也沒有測試,建議完整版。

方案三

office文檔轉PDF,PDF轉swf,使用flexpaper+swftools實如今線瀏覽。

在操做office2007時,需安裝SaveAsPDFandXPS.exe ,安裝成功後,如圖所示:

只有安裝了SaveAsPDFandXPS.exe,程序操做office文檔,纔有office文檔另存爲pdf文件。office2010不須要安裝了,內置有這個功能。

 核心代碼:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using Word = Microsoft.Office.Interop.Word;
  6 using Excel = Microsoft.Office.Interop.Excel;
  7 using PowerPoint = Microsoft.Office.Interop.PowerPoint;
  8 using Microsoft.Office.Core;
  9 namespace Wolfy.OfficePreview
 10 {
 11     /// <summary>
 12     /// Office2Pdf 將Office文檔轉化爲pdf
 13     /// </summary>
 14     public class Office2PDFHelper
 15     {
 16         public Office2PDFHelper()
 17         {
 18             //
 19             // TODO: 在此處添加構造函數邏輯
 20             //
 21         }
 22         /// <summary>
 23         /// Word轉換成pdf
 24         /// </summary>
 25         /// <param name="sourcePath">源文件路徑</param>
 26         /// <param name="targetPath">目標文件路徑</param>
 27         /// <returns>true=轉換成功</returns>
 28         public static bool DOCConvertToPDF(string sourcePath, string targetPath)
 29         {
 30             bool result = false;
 31             Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
 32             object paramMissing = Type.Missing;
 33             Word.ApplicationClass wordApplication = new Word.ApplicationClass();
 34             Word.Document wordDocument = null;
 35             try
 36             {
 37                 object paramSourceDocPath = sourcePath;
 38                 string paramExportFilePath = targetPath;
 39                 Word.WdExportFormat paramExportFormat = exportFormat;
 40                 bool paramOpenAfterExport = false;
 41                 Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
 42                 Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
 43                 int paramStartPage = 0;
 44                 int paramEndPage = 0;
 45                 Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
 46                 bool paramIncludeDocProps = true;
 47                 bool paramKeepIRM = true;
 48                 Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
 49                 bool paramDocStructureTags = true;
 50                 bool paramBitmapMissingFonts = true;
 51                 bool paramUseISO19005_1 = false;
 52                 wordDocument = wordApplication.Documents.Open(
 53                     ref paramSourceDocPath, ref paramMissing, ref paramMissing,
 54                     ref paramMissing, ref paramMissing, ref paramMissing,
 55                     ref paramMissing, ref paramMissing, ref paramMissing,
 56                     ref paramMissing, ref paramMissing, ref paramMissing,
 57                     ref paramMissing, ref paramMissing, ref paramMissing,
 58                     ref paramMissing);
 59                 if (wordDocument != null)
 60                     wordDocument.ExportAsFixedFormat(paramExportFilePath,
 61                         paramExportFormat, paramOpenAfterExport,
 62                         paramExportOptimizeFor, paramExportRange, paramStartPage,
 63                         paramEndPage, paramExportItem, paramIncludeDocProps,
 64                         paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
 65                         paramBitmapMissingFonts, paramUseISO19005_1,
 66                         ref paramMissing);
 67                 result = true;
 68             }
 69             catch
 70             {
 71                 result = false;
 72             }
 73             finally
 74             {
 75                 if (wordDocument != null)
 76                 {
 77                     wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
 78                     wordDocument = null;
 79                 }
 80                 if (wordApplication != null)
 81                 {
 82                     wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
 83                     wordApplication = null;
 84                 }
 85                 GC.Collect();
 86                 GC.WaitForPendingFinalizers();
 87                 GC.Collect();
 88                 GC.WaitForPendingFinalizers();
 89             }
 90             return result;
 91         }
 92 
 93         /// <summary>
 94         /// 把Excel文件轉換成PDF格式文件  
 95         /// </summary>
 96         /// <param name="sourcePath">源文件路徑</param>
 97         /// <param name="targetPath">目標文件路徑</param>
 98         /// <returns>true=轉換成功</returns>
 99         public static bool XLSConvertToPDF(string sourcePath, string targetPath)
100         {
101             bool result = false;
102             Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
103             object missing = Type.Missing;
104             Excel.ApplicationClass application = null;
105             Excel.Workbook workBook = null;
106             try
107             {
108                 application = new Excel.ApplicationClass();
109                 object target = targetPath;
110                 object type = targetType;
111                 workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
112                     missing, missing, missing, missing, missing, missing, missing, missing, missing);
113                 workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
114                 result = true;
115             }
116             catch
117             {
118                 result = false;
119             }
120             finally
121             {
122                 if (workBook != null)
123                 {
124                     workBook.Close(true, missing, missing);
125                     workBook = null;
126                 }
127                 if (application != null)
128                 {
129                     application.Quit();
130                     application = null;
131                 }
132                 GC.Collect();
133                 GC.WaitForPendingFinalizers();
134                 GC.Collect();
135                 GC.WaitForPendingFinalizers();
136             }
137             return result;
138         }
139         ///<summary>        
140         /// 把PowerPoint文件轉換成PDF格式文件       
141         ///</summary>        
142         ///<param name="sourcePath">源文件路徑</param>     
143         ///<param name="targetPath">目標文件路徑</param> 
144         ///<returns>true=轉換成功</returns> 
145         public static bool PPTConvertToPDF(string sourcePath, string targetPath)
146         {
147             bool result;
148             PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
149             object missing = Type.Missing;
150             PowerPoint.ApplicationClass application = null;
151             PowerPoint.Presentation persentation = null;
152             try
153             {
154                 application = new PowerPoint.ApplicationClass();
155                 persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
156                 result = true;
157             }
158             catch
159             {
160                 result = false;
161             }
162             finally
163             {
164                 if (persentation != null)
165                 {
166                     persentation.Close();
167                     persentation = null;
168                 }
169                 if (application != null)
170                 {
171                     application.Quit();
172                     application = null;
173                 }
174                 GC.Collect();
175                 GC.WaitForPendingFinalizers();
176                 GC.Collect();
177                 GC.WaitForPendingFinalizers();
178             }
179             return result;
180         }
181     }
182 }
Office2PDFHelper
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 namespace Wolfy.OfficePreview
 9 {
10     public partial class Office2PDF : System.Web.UI.Page
11     {
12         protected void Page_Load(object sender, EventArgs e)
13         {
14 
15         }
16         protected void btnWord_Click(object sender, EventArgs e)
17         {
18             Button btn = sender as Button;
19             switch (btn.CommandArgument)
20             {
21                 case "docx":
22                     Office2PDFHelper.DOCConvertToPDF(MapPath("/Doc/分析某網站的SEO策略(外鏈篇).doc"), MapPath("/PDF/分析某網站的SEO策略(外鏈篇).pdf"));
23                     break;
24                 case "xlsx":
25                     Office2PDFHelper.XLSConvertToPDF(MapPath("/Excel/1994-2013北京市歷年最低工資標準.xlsx"), MapPath("/PDF/1994-2013北京市歷年最低工資標準.pdf"));
26                     break;
27                 case "ppt":
28                     Office2PDFHelper.PPTConvertToPDF(MapPath("/PPT/23種設計模式詳解.ppt"), MapPath("/PDF/23種設計模式詳解.pdf"));
29                     break;
30                 default:
31                     break;
32             }
33         }
34     }
35 }
Office2PDF
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Office2PDF.aspx.cs" Inherits="Wolfy.OfficePreview.Office2PDF" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <title></title>
 9 </head>
10 <body>
11     <form id="form1" runat="server">
12     <div>
13       <asp:Button Text="Word轉PDF" ID="btnWord" runat="server" CommandArgument="docx" OnClick="btnWord_Click" />
14             <asp:Button ID="btnExcel" Text="Excel轉PDF" runat="server" CommandArgument="xlsx" OnClick="btnWord_Click" />
15             <asp:Button ID="btnPPT" Text="PPT轉PDF" runat="server" CommandArgument="ppt" OnClick="btnWord_Click" />
16     </div>
17     </form>
18 </body>
19 </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格式)

這裏只貼出核心代碼:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.UI;
 7 using System.Web.UI.WebControls;
 8 
 9 namespace Wolfy.OfficePreview
10 {
11     public partial class Office2Swf : System.Web.UI.Page
12     {
13         protected void Page_Load(object sender, EventArgs e)
14         {
15 
16         }
17         protected void btnWord_Click(object sender, EventArgs e)
18         {
19             Button btn = sender as Button;
20             switch (btn.CommandArgument)
21             {
22                 case "docx":
23                     ConvertOffice2Swf(MapPath("/Doc/分析某網站的SEO策略(外鏈篇).doc"), MapPath("/SWF/分析某網站的SEO策略(外鏈篇).swf"));
24                     break;
25                 case "xlsx":
26                     Office2PDFHelper.XLSConvertToPDF(MapPath("/Excel/1994-2013北京市歷年最低工資標準.xlsx"), MapPath("/SWF/1994-2013北京市歷年最低工資標準.swf"));
27                     break;
28                 case "ppt":
29                     Office2PDFHelper.PPTConvertToPDF(MapPath("/PPT/23種設計模式詳解.ppt"), MapPath("/SWF/23種設計模式詳解.swf"));
30                     break;
31                 default:
32                     break;
33             }
34         }
35         /// <summary>
36         /// office 轉swf
37         /// </summary>
38         /// <param name="officePath">要轉換的office文檔路徑</param>
39         /// <param name="swfPath">轉換後swf的路徑</param>
40         private void ConvertOffice2Swf(string officePath, string swfPath)
41         {
42             Process process = new Process();     //建立進程對象 
43             ProcessStartInfo startInfo = new ProcessStartInfo();
44             string paperroot = @"C:\Program Files\Macromedia\FlashPaper 2\FlashPrinter.exe";//這裏是FlashPrinter的路徑
45             string docFile = officePath;
46             string swfFile = swfPath;
47             startInfo.FileName = paperroot;
48             startInfo.Arguments = docFile + " -o " + swfFile;
49             startInfo.UseShellExecute = false;     //不使用系統外殼程序啓動 
50             startInfo.RedirectStandardInput = false;   //不重定向輸入 
51             startInfo.RedirectStandardOutput = false;   //重定向輸出 
52             startInfo.CreateNoWindow = true;     //不建立窗口 
53             process.StartInfo = startInfo;
54             process.Start();   
55             if (process != null)
56                 process.Close();
57            
58         }
59     }
60 }

鑑於測試時,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

相關文章
相關標籤/搜索