關於讀取和寫入word2003的書籤內容

目前的項目又要對word2003進行編程,主要功能是讀取和插入標籤的數據.具體代碼如下:
(打開word文檔與網上雷同)

引用部分:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Office;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;

打開word2003文檔,項目中的文檔模板實際是doc的文檔,dot的很不好用.
做doc文檔模板的時候不要用空格留空白,使用段落縮進的方式.標籤的添加等文檔格式完全編輯好再添加.
對於要預留空白的內容,通過插入1個只有1個單元格(無邊框)的方式來進行.這樣保證單元格以後內容位置固定,不會因爲插入了文字內容而移動位置,這隊固定格式公文很有好處.
打開word模板和word文件#region 打開word模板和word文件

        
public static void OpenWordDot()
        
{

        }


        
private void OpenWordDoc(string FileName, ref Microsoft.Office.Interop.Word.Document wDoc, ref  Microsoft.Office.Interop.Word.Application WApp)
        
{
            
if (FileName == ""return;
            Microsoft.Office.Interop.Word.Document thisDocument 
= null;
            Microsoft.Office.Interop.Word.FormFields formFields 
= null;
            Microsoft.Office.Interop.Word.Application thisApplication 
= new Microsoft.Office.Interop.Word.ApplicationClass();
            thisApplication.Visible 
= true;
            thisApplication.Caption 
= "";
            thisApplication.Options.CheckSpellingAsYouType 
= false;
            thisApplication.Options.CheckGrammarAsYouType 
= false;

            Object filename 
= FileName;
            Object ConfirmConversions 
= false;
            Object ReadOnly 
= true;
            Object AddToRecentFiles 
= false;

            Object PasswordDocument 
= System.Type.Missing;
            Object PasswordTemplate 
= System.Type.Missing;
            Object Revert 
= System.Type.Missing;
            Object WritePasswordDocument 
= System.Type.Missing;
            Object WritePasswordTemplate 
= System.Type.Missing;
            Object Format 
= System.Type.Missing;
            Object Encoding 
= System.Type.Missing;
            Object Visible 
= System.Type.Missing;
            Object OpenAndRepair 
= System.Type.Missing;
            Object DocumentDirection 
= System.Type.Missing;
            Object NoEncodingDialog 
= System.Type.Missing;
            Object XMLTransform 
= System.Type.Missing;

            
try
            
{
                Microsoft.Office.Interop.Word.Document wordDoc 
=
                 thisApplication.Documents.Open(
ref filename, ref ConfirmConversions,
                 
ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
                 
ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
                 
ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
                 
ref NoEncodingDialog, ref XMLTransform);

                thisDocument 
= wordDoc;
                wDoc 
= wordDoc;
                WApp 
= thisApplication;
                formFields 
= wordDoc.FormFields;
            }

            
catch (Exception ex)
            
{
                
            }


        }


        
#endregion

讀取文檔中標籤數據處理方法
1 獲取文檔中的標籤列表.把文檔對象的書籤列表讀到IEnumerator中.
2 通過枚舉推進的方式讀取每個書籤.
3 關閉文檔
//獲取標籤數據
        public string GetDocumentBookmarkData(string FileName)
        
{
 
            Microsoft.Office.Interop.Word.Document wDoc 
= null;
            Microsoft.Office.Interop.Word.Application wApp 
= null;
            
this.OpenWordDoc(FileName,ref wDoc, ref wApp);
            
object oEndOfDoc = "\\endofdoc";
            
object missing = System.Reflection.Missing.Value; 

            
string str="";

            System.Collections.IEnumerator enu
=wApp.ActiveDocument.Bookmarks.GetEnumerator();

            
while(enu.MoveNext())
            
{
                Microsoft.Office.Interop.Word.Bookmark bk 
= (Microsoft.Office.Interop.Word.Bookmark)enu.Current;

                str 
+= "{"+bk.Name.ToString() + ":"+bk.Range.Text+"}";
            }


            
object o = null;

            wDoc.Close(
ref missing, ref missing, ref missing);
            wApp.Quit(
ref missing, ref missing, ref missing);

            
if (wDoc!=null)
            
{
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
                wDoc 
= null;
            }


            
if (wApp != null)
            
{
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
                wApp 
= null;
            }


            GC.Collect();

            
return str;
        }


往書籤中寫入數據
1 把書籤的名字通過枚舉的方式讀出來,寫到數組裏(圖/表格等特殊數據書籤要處理掉)
2 讀取數據庫數據表內容寫入書籤初.注意技巧.
    a 檢查文檔書籤集合中存在書籤
    b 獲取文檔書籤,並選擇他,寫入數據到selection
    c 移動書籤的end到合適位置,否則讀書籤數據永遠只讀到書籤定義處的字符.
    d 對於圖/表格等的插入需要特殊處理.
    e 掃尾 另存.不要覆蓋原來模板哦
 //設定標籤的數據
        public string SetDocumentBookmarkData(string FileName,System.Data.DataTable dt)
        
{
            
//打開文檔
            Microsoft.Office.Interop.Word.Document wDoc = null;
            Microsoft.Office.Interop.Word.Application wApp 
= null;
            
this.OpenWordDoc(FileName, ref wDoc, ref wApp);
            
object oEndOfDoc = "\\endofdoc";
            
object missing = System.Reflection.Missing.Value;

            
//設定標籤數據
            System.Collections.IEnumerator enu = wApp.ActiveDocument.Bookmarks.GetEnumerator();

            
string[] strbook=new string[dt.Columns.Count-1];
            
int i=0;
            Microsoft.Office.Interop.Word.Bookmark bk
=null;
            
while (enu.MoveNext())
            
{
                bk 
= (Microsoft.Office.Interop.Word.Bookmark)enu.Current;

                
if (bk.Name.ToString().Trim()!="Table")
                
{
                    strbook[i] 
= bk.Name.ToString();
                    i
++;
                }

            }


            
object tempobject=null;
            
int length = 0;
            
for (i = 0; i < strbook.Length;i++ )
            
{
                tempobject 
= strbook[i].ToString();

                
if (wApp.ActiveDocument.Bookmarks.Exists(strbook[i].ToString()))
                
{
                    wApp.ActiveDocument.Bookmarks.get_Item(
ref tempobject).Select();

                    wApp.Selection.Text 
= dt.Rows[0][strbook[i]].ToString();

                    length 
= dt.Rows[0][strbook[i]].ToString().Length;
                    wApp.ActiveDocument.Bookmarks.get_Item(
ref tempobject).End = wApp.ActiveDocument.Bookmarks.get_Item(ref tempobject).End + length;
                }


            }


            InsertTabletoBookmark(
"Table",ref wDoc, ref wApp);

            
            
//收尾工作
            object o = null;

            
string guid = System.Guid.NewGuid().ToString();
            
object sFileName = "D:/Test/office/word/" + guid + ".doc";
            
            
if (wDoc.SaveFormat == (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument)
            
{
                wDoc.Application.ActiveDocument.SaveAs(
ref sFileName, ref missing, ref missing,
                
ref missing, ref missing, ref missing,
                
ref missing, ref missing,
                
ref missing, ref missing,
                
ref missing, ref missing, ref missing,
                
ref missing, ref missing, ref missing);
            }


            wDoc.Close(
ref missing, ref missing, ref missing);
            wApp.Quit(
ref missing, ref missing, ref missing);

            
if (wDoc != null)
            
{
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
                wDoc 
= null;
            }


            
if (wApp != null)
            
{
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
                wApp 
= null;
            }


            GC.Collect();

            
return guid + ".doc";
        }


表格的插入方法
1  表格的插入很簡單,圖表可參照
2  表格插入後如何獲取表格請注意.用書籤的Range對象的Tables集合
插入表格數據#region 插入表格數據

        
private bool InsertTabletoBookmark(string objTable,ref Microsoft.Office.Interop.Word.Document wDoc, ref  Microsoft.Office.Interop.Word.Application WApp)
        
{
            
object oEndOfDoc = "\\endofdoc";
            
object missing = System.Reflection.Missing.Value;

            
object objBookmark = objTable;

            WApp.ActiveDocument.Bookmarks.get_Item(
ref objBookmark).Select();

            Microsoft.Office.Interop.Word.Table table 
= wDoc.Tables.Add(WApp.Selection.Range, 34ref missing, ref missing);
            table.Cell(
11).Range.Text = "表:" + WApp.ActiveDocument.Bookmarks.get_Item(ref objBookmark).Range.Tables[1].Rows.Count;

            
return true;
        }


結束語
由於生成文檔用戶修改後往往會丟掉書籤,數據就讀不到了,所以生成文檔還不能提交給用戶修改保存,那位有辦法的歡迎指教.

http://www.cnblogs.com/Andmm/archive/2008/06/10/1216875.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章