利用Word.Application提供的方法,可以很轻易地将Word文档转化为HTML等其它格式,下面就是实现的全部的代码:
VisualC#
WordToHtml.aspx
Inherits="aspxWebcs.WordToHtml"%>
HTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
WordToHtml
/intellisense/ie5">
WordToHtml.aspx.cs
usingSystem;
usingSystem.Collections;
ponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Web;
usingSystem.Web.SessionState;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.HtmlControls;
usingOffice;
namespaceaspxWebcs
{
///
///WordToHtml的摘要说明。
///首先要添加引用:MicrosoftWord9.0ObjectLibrary
///
publicclassWordToHtml:System.Web.UI.Page
{
privatevoidPage_Load(objectsender,System.EventArgse)
{
//在此处放置用户代码以初始化页面
Word.ApplicationClassword=newWord.ApplicationClass();
TypewordType=word.GetType();
Word.Documentsdocs=word.Documents;
//打开文件
TypedocsType=docs.GetType();
objectfileName="d:\\tmp\\aaa.doc";
Word.Documentdoc=(Word.Document)docsType.InvokeMember("Open",
System.Reflection.BindingFlags.InvokeMethod,null,docs,newObject[]{fileName,true,true});
//转换格式,另存为
TypedocType=doc.GetType();
objectsaveFileName="d:\\tmp\\aaa.html";
//下面是MicrosoftWord9ObjectLibrary的写法,如果是10,可能写成:
//docType.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,
null,doc,newobject[]{saveFileName,Word.WdSaveFormat.wdFormatFilteredHTML});
///其它格式:
///wdFormatHTML
///wdFormatDocument
///wdFormatDOSText
///wdFormatDOSTextLineBreaks
///wdFormatEncodedText
///wdFormatRTF
///wdFormatTemplate
///wdFormatText
///wdFormatTextLineBreaks
///wdFormatUnicodeText
docType.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,
null,doc,newobject[]{saveFileName,Word.WdSaveFormat.wdFormatHTML});
//退出Word
wordType.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,
null,word,null);
}
#regionWeb窗体设计器生成的代码
overrideprotectedvoidOnInit(EventArgse)
{
//
//CODEGEN:该调用是Web窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///
privatevoidInitializeComponent()
{
this.Load+=newSystem.EventHandler(this.Page_Load);
}
#endregion
}
}