word 要操作Word,我們就需要Word的物件程式庫檔案“MSWORD.OLB”(word 2000為MSWORD9.OLB),通常安裝了Office Word後,你就可以在office安裝目錄的Office10檔案夾下面找到這個檔案,當我們將這個檔案引入到項目後,我們就可以在源碼中使用各種操作函數來操作Word。具體做法是開啟功能表列中的項目>添加引用>瀏覽,在開啟的“選擇組件”對話方塊中找到MSWORD.OLB後按確定即可引入此物件程式庫檔案,vs.net將會自動將 庫檔案轉化為DLL組件,這樣我們只要在源碼中建立該組件對象即可達到操作Word的目的!
在CS代碼檔案中對命名空間的應用,如:using Word;範例如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Word;
namespace ExamSecure
{
///
/// ItemToDoc 的摘要說明。
///
public class ItemToDoc : System.Windows.Forms.Form
{
object strFileName;
Object Nothing;
Word.ApplicationClass myWordApp=new Word.ApplicationClass();
Word.Document myWordDoc;
string strContent="";
private System.ComponentModel.Container components = null;
public ItemToDoc()
{
//
// Windows 表單設計器支援所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 調用後添加任何建構函式代碼
//
}
[STAThread]
static void Main()
{
System.Windows.Forms.Application.Run(new ItemToDoc());
}
///
/// 清理所有正在使用的資源。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// 設計器支援所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
///
private void InitializeComponent()
{
//
// ItemToDoc
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "ItemToDoc";
this.Text = "ItemToDoc";
this.Load += new System.EventHandler(this.ItemToDoc_Load);
}
#endregion
private void ItemToDoc_Load(object sender, System.EventArgs e)
{
WriteFile();
}
private void WriteFile()
{
strFileName=System.Windows.Forms.Application.StartupPath+"\\試題庫【"+GetRandomString()+"】.doc";
Object Nothing=System.Reflection.Missing.Value;
myWordDoc=myWordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
#region 將資料庫中讀取得資料寫入到word檔案中
strContent="試題庫\n\n\r";
WriteFile(strContent);
strContent="試題庫";
WriteFile(strContent);
#endregion
//將WordDoc文檔對象的內容儲存為DOC文檔
myWordDoc.SaveAs(ref strFileName,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
//關閉WordDoc文檔對象
myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//關閉WordApp組件對象
myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
}
///
/// 擷取一個隨即字串
///
///
private string GetRandomString()
{
DateTime iNow=DateTime.Now;
string strDate=iNow.ToString("yyyyMMddHHmmffff");
Random ran=new Random();
int iRan=Convert.ToInt32(10000*ran.NextDouble());
string strRan=iRan.ToString();
//位元不足則補0
int iRanlen=strRan.Length;
for(int i=0;i<4-iRanlen;i++)
{
strRan="0"+strRan;
}
return strDate+strRan;
}
///
/// 將字串寫入到Word檔案中
///
/// 要寫入的字串
private void WriteFile(string str)
{
myWordDoc.Paragraphs.Last.Range.Text=str;
}
}
}