C#读取和写入word2003的书签内容(怪,新,全)

系统 1450 0
文/Andmm  出处/博客园

目前的项目又要对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 = bk.Name.ToString();
                    i++;
                }
            }

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

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

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

                    length = dt.Rows[0][strbook].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, 3, 4, ref missing, ref missing);
            table.Cell(1, 1).Range.Text = "表:" + WApp.ActiveDocument.Bookmarks.get_Item(ref objBookmark).Range.Tables[1].Rows.Count;

            return true;
        }#endregion



结束语
由于生成文档用户修改后往往会丢掉书签,数据就读不到了,所以生成文档还不能提交给用户修改保存,那位有办法的欢迎指教.

C#读取和写入word2003的书签内容(怪,新,全)


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论