.NET實現在網頁中預覽Office文件的3個方法_.Net教程
推薦:asp.net中控制反轉怎么理解?對IOC的解釋為:Inversion of control is a common characteristic of frameworks, so saying that these lightweight containers are special because they use inversion of control is like saying my car is special because it has wheels. 我想對這一概念執行
近日公司要搞一個日常的文檔管理的東東,可以上傳、下載各種文件,如果是office文件呢還必須得支持預覽功能,其他的都好說但是唯獨office預覽功能比較麻煩,但是不能不做,廢話不多說了一步步來吧。分析了下網易郵箱的文件預覽功能,他用的是微軟的組件,最早叫Office online,現在分開了叫Word online、Excel online ....等等,效果十分炫酷功能十分強大,但是查看了下對api的說明發現對服務器的要求比較苛刻而且配置比較復雜不太適合。然后 又看了下騰訊用的是永中第三方組件,效果嘛自然比不上微軟的但是能用,綜合網上的一些資料大概也就那么幾種方式實現
1.使用Microsoft的Office組件將文件直接轉換為html文件(優點:代碼實現最簡單,工作強度最小。缺點:效果極差)
2.使用Microsoft的Office組件將文件轉換為PDF格式文件,然后再使用pdf2swf轉換為swf文件,也就是flash文件在使用FlexPaper展示出來(優點:預覽效果能接受,缺點:代碼量大)
效果如圖:
3. 使用Office online(優點:表現完美,缺點:不適合中小企業應用)
綜合考慮決定使用第二種方法,經過次次波折終于可以使用,但是有個問題至今沒有得到解決,調用Office組件的時候有時候會出現如下異常:
檢索 COM 類工廠中 CLSID 為 {000209FF-0000-0000-C000-000000000046} 的組件失敗,原因是出現以下錯誤: 8000401a 因為配置標識不正確,系統無法開始服務器進程。請檢查用戶名和密碼。 (異常來自 HRESULT:0x8000401A),查閱無數資料還是不能解決,最讓人不可接受的的是office文件必須標標準準毫無容錯能力,當轉換ppt文件時竟然會彈出轉換進度框!!
好吧!那么我們改進它。
使用ASPOSE+pdf2swf+FlexPaper
關于ASPOSE大家可以到官網了解,這是款商業收費產品但是免費也可以使用
1、引用dll
2、編寫轉換幫助類
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Cells;
using Aspose.Words;
using Aspose.Slides;
using System.Text.RegularExpressions;
using System.IO;
namespace Souxuexiao.Common
{
/// <summary>
/// 第三方組件ASPOSE Office/WPS文件轉換
/// Writer:Helen Joe
/// Date:2014-09-24
/// </summary>
public class AsposeUtils
{
/// <summary>
/// PFD轉換器位置
/// </summary>
private static string _EXEFILENAME = System.Web.HttpContext.Current != null
? System.Web.HttpContext.Current.Server.MapPath("/pdf2swf/pdf2swf.exe")
: System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\pdf2swf\\pdf2swf.exe");
#region 1.01 Wrod文檔轉換為PDF文件 +ConvertDocToPdF(string sourceFileName, string targetFileName)
/// <summary>
/// Wrod文檔轉換為PDF文件
/// </summary>
/// <param name="sourceFileName">需要轉換的Word全路徑</param>
/// <param name="targetFileName">目標文件全路徑</param>
/// <returns>轉換是否成功</returns>
public static bool ConvertDocToPdF(string sourceFileName, string targetFileName)
{
Souxuexiao.API.Logger.error(string.Format("Wrod文檔轉換為PDF文件:sourceFileName={0},targetFileName={1}", sourceFileName, targetFileName));
try
{
using (System.IO.Stream stream = new System.IO.FileStream(sourceFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
Document doc = new Document(sourceFileName);
doc.Save(targetFileName, Aspose.Words.SaveFormat.Pdf);
}
}
catch (Exception ex)
{
Souxuexiao.API.Logger.error(string.Format("Wrod文檔轉換為PDF文件執行ConvertDocToPdF發生異常原因是:{0}",ex.Message));
}
return System.IO.File.Exists(targetFileName);
}
#endregion
分享:delphi選擇文件夾例子所需單元 示例代碼
- 相關鏈接:
- 教程說明:
.Net教程-.NET實現在網頁中預覽Office文件的3個方法。