C#操作Word (2)-- 打開&關閉Word文檔


本文正式開始在VS2010中使用C#語言操作Word2007.

不是十分了解Word對象模型的朋友,請參考上一篇文章,或者下載:C#操作Word2007.pdf

 

----------------------------------華麗分割--------------------------------------------

1.添加Reference,添加命名空間

新建一個Winform工程后,首先需要給工程添加Reference

由於我的Word是2007的,所以我選擇了 Microsoft Word 12.0 Object Library,

添加完成后,在Reference表單中應該多出如下兩個條目:

Microsoft.Office.Core

Microsoft.Office.InterOP.Word

--------------------------------------------------------------------------

下面就正式開始編寫C#代碼了挖。

首先,在你的Form1.cs中添加Word命名空間:我添加的是:

 

[csharp]  view plaincopy
  1. using MSWord    =   Microsoft.Office.Interop.Word;  

 

 

2.打開Word文檔

然后給Form添加一個Load事件的消息響應函數OnLoad:

 

 

好了。下一步,我們完善OnLoad函數:

 

[csharp]  view plaincopy
  1. private MSWord.Application m_word;  
  2. private MSWord.Document m_doc;  
  3.   
  4.         public Form1()  
  5.         {  
  6.             InitializeComponent();  
  7.         }  
  8.           
  9.         private void OnLoad(object sender, EventArgs e)  
  10.         {  
  11.             m_word = new MSWord.Application();  
  12.         }   

在OnLoad中我們實例化了一個Word的Application對象,代表Word2007應用程序。

 

 

這樣只打開了一個應用程序的空殼,里面還沒有文檔。下面我們就打開一個已有的文檔吧。

在打開之前,我們先添加一個按鈕,然后為其設置Click事件的監聽器OnOpen()

 

[csharp]  view plaincopy
  1. private void OnOpen(object sender, EventArgs e)  
  2.         {  
  3.   
  4.             Object filename = "test.docx";  
  5.             Object filefullname = @"C:\Users\David_ss\Desktop\項目管理\test.docx";  
  6.             Object confirmConversions = Type.Missing;  
  7.             Object readOnly = Type.Missing;  
  8.             Object addToRecentFiles = Type.Missing;  
  9.             Object passwordDocument = Type.Missing;  
  10.             Object passwordTemplate = Type.Missing;  
  11.             Object revert = Type.Missing;  
  12.             Object writePasswordDocument = Type.Missing;  
  13.             Object writePasswordTemplate = Type.Missing;  
  14.             Object format = Type.Missing;  
  15.             Object encoding = Type.Missing;  
  16.             Object visible = Type.Missing;  
  17.             Object openConflictDocument = Type.Missing;  
  18.             Object openAndRepair = Type.Missing;  
  19.             Object documentDirection = Type.Missing;  
  20.             Object noEncodingDialog = Type.Missing;  
  21.   
  22.             for (int i = 1; i <= m_word.Documents.Count; i++)  
  23.             {  
  24.                 String str = m_word.Documents[i].FullName.ToString();  
  25.                 if (str == filefullname.ToString())  
  26.                 {  
  27.                     MessageBox.Show("請勿重復打開該文檔");  
  28.                     return;  
  29.                 }  
  30.             }  
  31.             try  
  32.             {  
  33.                 m_word.Documents.Open(ref filefullname,  
  34.                         ref confirmConversions, ref readOnly, ref addToRecentFiles,  
  35.                         ref passwordDocument, ref passwordTemplate, ref revert,  
  36.                         ref writePasswordDocument, ref writePasswordTemplate,  
  37.                         ref format, ref encoding, ref visible, ref openConflictDocument,  
  38.                         ref openAndRepair, ref documentDirection, ref noEncodingDialog  
  39.                         );  
  40.                 m_word.Visible = true;  
  41.   
  42.                 //MessageBox.Show(m_word.Documents.Count.ToString());  
  43.                 //MessageBox.Show(m_word.Documents[1].FullName.ToString());  
  44.             }  
  45.             catch (System.Exception ex)  
  46.             {  
  47.                 MessageBox.Show("打開Word文檔出錯");  
  48.             }  
  49.         }   


可以看到,這里調用的是Documents對象的Open方法,參數很多,感興趣的朋友可以參考MSDN。

 

上面代碼中我直接寫出了文件路徑,當然更好的方法是彈出對話框然后選擇文件。

代碼中也檢查了該文檔是否已經打開,這樣也就避免了重復打開同一文檔兩次。另外需要注意的是,Word應用程序打開文檔的數量是從1開始數的(即1 based),不是常見的從0開始,這點需要注意一下:

for(int i=1;i<m_word.Documents.Count;i++)

 

在Open方法調用完成后,別忘記把application對象的visiable屬性設置為True,否則你是看不到打開的文檔的。

 

OK,可以編譯運行啦。如下圖:

 

3.查看Word文檔信息

下面,我們來看一下文檔的有關信息,對應上圖中的文檔信息按鈕(監聽器OnShowInfo):

 

[csharp]  view plaincopy
  1. private void OnShowInfo(object sender, EventArgs e)  
  2.       {  
  3.           System.Diagnostics.Debug.WriteLine("當前打開文檔數量: "+m_word.Documents.Count.ToString()+"\n");  
  4.           System.Diagnostics.Debug.WriteLine(m_word.ActiveDocument.Paragraphs.Count.ToString());  
  5.       }   


由於Word里面的對象屬性實在是太多,這里也就隨便選擇兩個吧。第一行是當前打開文檔數量,第二行是當前激活的文檔的自然段個數:

 

可以看到分別輸出1和2,沒錯吧。

4.關閉Word文檔,退出Word應用程序

最后,我們再來看看如何關閉吧,同樣的,先添加按鈕,然后添加OnClose()監聽器。

 

[csharp]  view plaincopy
  1. private void OnClose(object sender, EventArgs e)  
  2.       {  
  3.           //避免彈出normal.dotm被使用的對話框,自動保存模板  
  4.           m_word.NormalTemplate.Saved = true;  
  5.   
  6.           //先關閉打開的文檔(注意saveChanges選項)  
  7.           Object saveChanges = MSWord.WdSaveOptions.wdSaveChanges;  
  8.           Object originalFormat = Type.Missing;  
  9.           Object routeDocument = Type.Missing;  
  10.           m_word.Documents.Close(ref saveChanges,ref originalFormat, ref routeDocument);  
  11.             
  12.           //若已經沒有文檔存在,則關閉應用程序  
  13.           if (m_word.Documents.Count == 0)  
  14.           {  
  15.               m_word.Quit(Type.Missing, Type.Missing, Type.Missing);  
  16.           }  
  17.             
  18.       }  


這里面需要注意的是為了防止彈出 normal.dotm被使用的對話框,最好先自動保存模板。

 

然后設置好你需要的saveOption.有三種,分別是

 

  • wdSaveChanges
  • wdDoNotSaveChanges
  • wdPromptToSaveChanges
OK,今天就介紹這么多吧。下次再介紹有關Selection對象和Range對象吧。
 
-------------------------------華麗分割--------------------------------------
 

 

MSDN------>Word.Document對象


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM