本文是應在ASP.NET里創(chuàng)建Microsoft Word文檔之需而寫的。這篇文章演示了在ASP.NET里怎么創(chuàng)建和修改Microsoft Word文檔。
[背景]
自動化是一種能讓各種語言編寫的(如:Visual Basic.NET或C#)應用程序在程序級別上控制其他應用程序。
對于Word的自動化允許你執(zhí)行諸如創(chuàng)建新的文檔,向文檔里添加文本,郵件合并和格式化文檔這些操作。在Word和其他的Microsoft Office程序里,那些通過用戶接口進行的可視化操作也可以通過程序級別的自動化來實現(xiàn)。
Word通過對象模型把這個程序可操作的功能向外提供了使用接口。
對象模型是一組類和方法的集合,這些類和方法與Word的邏輯組件構(gòu)成對應。例如,他可能是應用程序?qū)ο,文檔對象,段落對象,每一個對象都包含了Word組件的功能。
[建立工程]
在.NET里操作Word的第一步就是添加COM引用到你的工程里,通過右鍵點擊Solution Explorer的Reference,Add Reference。選擇COM選項卡,查找Microsoft Word 10.0 Object Library。點擊選擇,OK。
這將把封裝有Word的COM的程序集自動的添加到應用程序目錄里。
現(xiàn)在,你可以建立一個Word的實例了:
Word.ApplicationClass oWordApp = new Word.ApplicationClass();
你可以調(diào)用Word提供給你的方法和屬性來操縱Word文檔。
學習如何使用Word,Excel,Powerpoint的對象模型最好的途徑就是使用在這些Office應用里使用Macro Recorder:
1.在Tools菜單的Macro選項里選擇 Record New Macro ,并且執(zhí)行你有興趣的任務。
2.在Tools菜單的Macro選項里選擇 Stop Recording。
3.如果你進行了紀錄,選擇Tools菜單的Macro選項里的Macros,找到你記錄的宏,你可以編輯它。
上面的操作產(chǎn)生了VBA代碼來完成你記錄的任務。需要注意的是,宏在大多數(shù)情況下不是最好的代碼,但是它提供了一種便捷和可用的方法。
下面例子打開并添加一寫文字:
object fileName = "c:\\database\\test.doc";
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
Word.ApplicationClass oWordApp = new Word.ApplicationClass();
Word.Document oWordDoc = oWordApp.Documents.Open(ref fileName, ref missing,ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing);
oWordDoc.Activate();
oWordApp.Selection.TypeText("This is the text");
oWordApp.Selection.TypeParagraph();
oWordDoc.Save();
oWordApp.Application.Quit(ref missing, ref missing, ref missing);
如果創(chuàng)建一個新文檔并保存是這樣寫的:
Word.ApplicationClass oWordApp = new Word.ApplicationClass();
Word.Document oWordDoc = oWordApp.Documents.Add(ref missing, ref missing,ref missing, ref missing);
oWordDoc.Activate();
oWordApp.Selection.TypeText("This is the text");
oWordApp.Selection.TypeParagraph();
oWordDoc.SaveAs("c:\\myfile.doc");
oWordApp.Application.Quit(ref missing, ref missing, ref missing);
在C#里,Word文檔類的打開方法是這樣定義的:Open(ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object, ref object)。在C#里的打開方法需要15個參數(shù),并且每個參數(shù)必須被ref關鍵字所描述,而且是object類型。
第一個參數(shù)是文件,名,在Visual Basic.NET里通常是一個String,但是在在C#里,它必須是一個包含有String的object,代碼是這樣的:
object fileName = "c:\\database\\test.doc";
雖然我們僅需要使用Open方法的第一個參數(shù),但是C#不允許使用默認參數(shù),所以我們賦予它14個object類型的值:System.Reflection.Missing.Value
[使用模版]
如果你需要自動的建立有通用格式的文檔,那你可以使用基于預格式化的摸版來建立新文檔,這樣可以方便很多。
在Word里使用摸版而不是建立空文檔有兩個明顯的優(yōu)點:
1.你可以更大程度的格式化文檔和控制文檔里的對象。
2.可以用較少的代碼建立文檔。 通過使用摸版,你可以調(diào)整表格、段落和其他一些在文檔里的對象的位置,同時包括格式化這些對象。通過使用自動化處理,你可以建立一個基于摸版的文檔,代碼如下:
Word.ApplicationClass oWordApp = new Word.ApplicationClass();
object oTemplate = "c:\\MyTemplate.dot";
oWordDoc = oWordApp.Documents.Add(ref oTemplate, ref Missing,ref Missing, ref Missing);
|
| |