本文正式開始在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命名空間:我添加的是:
- using MSWord = Microsoft.Office.Interop.Word;
2.打開Word文檔
然后給Form添加一個Load事件的消息響應函數OnLoad:
好了。下一步,我們完善OnLoad函數:
- private MSWord.Application m_word;
- private MSWord.Document m_doc;
- public Form1()
- {
- InitializeComponent();
- }
- private void OnLoad(object sender, EventArgs e)
- {
- m_word = new MSWord.Application();
- }
在OnLoad中我們實例化了一個Word的Application對象,代表Word2007應用程序。
這樣只打開了一個應用程序的空殼,里面還沒有文檔。下面我們就打開一個已有的文檔吧。
在打開之前,我們先添加一個按鈕,然后為其設置Click事件的監聽器OnOpen()
- private void OnOpen(object sender, EventArgs e)
- {
- Object filename = "test.docx";
- Object filefullname = @"C:\Users\David_ss\Desktop\項目管理\test.docx";
- Object confirmConversions = Type.Missing;
- Object readOnly = Type.Missing;
- Object addToRecentFiles = Type.Missing;
- Object passwordDocument = Type.Missing;
- Object passwordTemplate = Type.Missing;
- Object revert = Type.Missing;
- Object writePasswordDocument = Type.Missing;
- Object writePasswordTemplate = Type.Missing;
- Object format = Type.Missing;
- Object encoding = Type.Missing;
- Object visible = Type.Missing;
- Object openConflictDocument = Type.Missing;
- Object openAndRepair = Type.Missing;
- Object documentDirection = Type.Missing;
- Object noEncodingDialog = Type.Missing;
- for (int i = 1; i <= m_word.Documents.Count; i++)
- {
- String str = m_word.Documents[i].FullName.ToString();
- if (str == filefullname.ToString())
- {
- MessageBox.Show("請勿重復打開該文檔");
- return;
- }
- }
- try
- {
- m_word.Documents.Open(ref filefullname,
- ref confirmConversions, ref readOnly, ref addToRecentFiles,
- ref passwordDocument, ref passwordTemplate, ref revert,
- ref writePasswordDocument, ref writePasswordTemplate,
- ref format, ref encoding, ref visible, ref openConflictDocument,
- ref openAndRepair, ref documentDirection, ref noEncodingDialog
- );
- m_word.Visible = true;
- //MessageBox.Show(m_word.Documents.Count.ToString());
- //MessageBox.Show(m_word.Documents[1].FullName.ToString());
- }
- catch (System.Exception ex)
- {
- MessageBox.Show("打開Word文檔出錯");
- }
- }
可以看到,這里調用的是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):
- private void OnShowInfo(object sender, EventArgs e)
- {
- System.Diagnostics.Debug.WriteLine("當前打開文檔數量: "+m_word.Documents.Count.ToString()+"\n");
- System.Diagnostics.Debug.WriteLine(m_word.ActiveDocument.Paragraphs.Count.ToString());
- }
由於Word里面的對象屬性實在是太多,這里也就隨便選擇兩個吧。第一行是當前打開文檔數量,第二行是當前激活的文檔的自然段個數:
可以看到分別輸出1和2,沒錯吧。
4.關閉Word文檔,退出Word應用程序
最后,我們再來看看如何關閉吧,同樣的,先添加按鈕,然后添加OnClose()監聽器。
- private void OnClose(object sender, EventArgs e)
- {
- //避免彈出normal.dotm被使用的對話框,自動保存模板
- m_word.NormalTemplate.Saved = true;
- //先關閉打開的文檔(注意saveChanges選項)
- Object saveChanges = MSWord.WdSaveOptions.wdSaveChanges;
- Object originalFormat = Type.Missing;
- Object routeDocument = Type.Missing;
- m_word.Documents.Close(ref saveChanges,ref originalFormat, ref routeDocument);
- //若已經沒有文檔存在,則關閉應用程序
- if (m_word.Documents.Count == 0)
- {
- m_word.Quit(Type.Missing, Type.Missing, Type.Missing);
- }
- }
這里面需要注意的是為了防止彈出 normal.dotm被使用的對話框,最好先自動保存模板。
然后設置好你需要的saveOption.有三種,分別是
- wdSaveChanges
- wdDoNotSaveChanges
- wdPromptToSaveChanges