新书推介:《语义网技术体系》
作者:瞿裕忠,胡伟,程龚
   XML论坛     W3CHINA.ORG讨论区     计算机科学论坛     SOAChina论坛     Blog     开放翻译计划     新浪微博  
 
  • 首页
  • 登录
  • 注册
  • 软件下载
  • 资料下载
  • 核心成员
  • 帮助
  •   Add to Google

    >> 本版讨论.NET,C#,ASP,VB技术
    [返回] 中文XML论坛 - 专业的XML技术讨论区计算机技术与应用『 Dot NET,C#,ASP,VB 』 → [原创]C#操作Word 查看新帖用户列表

      发表一个新主题  发表一个新投票  回复主题  (订阅本版) 您是本帖的第 10763 个阅读者浏览上一篇主题  刷新本主题   树形显示贴子 浏览下一篇主题
     * 贴子主题: [原创]C#操作Word 举报  打印  推荐  IE收藏夹 
       本主题类别:     
     binaryluo 帅哥哟,离线,有人找我吗?
      
      
      威望:6
      等级:研二(Pi-Calculus看得一头雾水)(版主)
      文章:679
      积分:5543
      门派:IEEE.ORG.CN
      注册:2005/2/19

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给binaryluo发送一个短消息 把binaryluo加入好友 查看binaryluo的个人资料 搜索binaryluo在『 Dot NET,C#,ASP,VB 』的所有贴子 引用回复这个贴子 回复这个贴子 查看binaryluo的博客楼主
    发贴心情 [原创]C#操作Word

    C#操作Office套件的时候都需要用到COM组件,需要在项目里添加相应的COM组件。用C#在Word里查找指定关键字的方法有两种:Selection对象和Range对象。

         Selection对象的用法:
         // C#
          internal void SelectionFind()
         {
             string strFind = "find me";
             Word.Find fnd = ThisApplication.Selection.Find;
              fnd.ClearFormatting();
              fnd.Text = strFind;
             object missingValue = Type.Missing;

             if (fnd.Execute(ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue))
            {
                   MessageBox.Show("Text found.");
             }
             else
             {
                   MessageBox.Show("The text could not be located.");
              }
    }
        
         Range对象的用法:
         // C#
        internal void RangeFind()
       {
           Word.Range rng = ThisDocument.Paragraphs[2].Range;
           Word.Find fnd = rng.Find;
           fnd.ClearFormatting();
           object missingValue = Type.Missing;
           object findStr = "find me";
           if (fnd.Execute(ref findStr, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue,
                                    ref missingValue, ref missingValue, ref missingValue))
           {
                    MessageBox.Show("Text found.");
           }
           else
           {
                    MessageBox.Show("Text not found.");
            }
                    rng.Select();
            }

         下面是我自己写的一段完整的代码,功能:在一个指定的Word文档中查找指定的关键字,并打印出包含该关键字的段落。使用的Range对象。

    using System;
    using System.Collections;
    using Word;

    namespace SearchWordDoc
    {
        /// <summary>
        /// SearchWordDoc's summary
        /// </summary>
        public class SearchWordDoc     
        {
            // search word in document.
            // strName is the document name which is searched.
            // strFind is the key word or phrase.
            // return the match paragraphs.
            public ArrayList swd(string strFName, string strFind)
            {
                ArrayList textsFound = new ArrayList();  // matched texts
                object missingValue = Type.Missing;
                Word.ApplicationClass wdApp = null;      // Word Application object
               
                try
                {
                    object fName = strFName as object;
                    wdApp = new ApplicationClass();      // create a Word application object
                    Word.Document wdDoc = wdApp.Documents.Open(ref fName, ref missingValue,
                        ref missingValue, ref missingValue, ref missingValue,
                        ref missingValue, ref missingValue, ref missingValue,
                        ref missingValue, ref missingValue, ref missingValue,
                        ref missingValue, ref missingValue, ref missingValue,
                        ref missingValue, ref missingValue); // open a Word object
                   
                    // the Word object has paragraphs or not
                    if (wdDoc.Paragraphs != null && wdDoc.Paragraphs.Count > 0)
                    {
                        int count = wdDoc.Paragraphs.Count;  // the number of doc paragraphs
                        Word.Range rng;                      // Word.Range object
                        Word.Find fnd;                       // Word.Find object

                        Console.WriteLine("There are {0} paragraphs in document '{1}'.", count, strFName);

                        for (int i = 1; i <= count; ++ i)    // search key words in every paragraphs
                        {
                            rng = wdDoc.Paragraphs[i].Range;
                            fnd = rng.Find;
                            fnd.ClearFormatting();
                            fnd.Text = strFind;

                            if (fnd.Execute(ref missingValue, ref missingValue,
                                ref missingValue, ref missingValue, ref missingValue,
                                ref missingValue, ref missingValue, ref missingValue,
                                ref missingValue, ref missingValue, ref missingValue,
                                ref missingValue, ref missingValue, ref missingValue,
                                ref missingValue))
                            {
                                // if find the matched paragrahps, add it into the textsFound ArrayList.
                                textsFound.Add("[" + i.ToString() + "] " + wdDoc.Paragraphs[i].Range.Text.Trim());
                            }
                        }
                    }
                }
                catch (NullReferenceException e)
                {
                    Console.WriteLine(e.ToString());
                    wdApp.Quit(ref missingValue, ref missingValue, ref missingValue);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    wdApp.Quit(ref missingValue, ref missingValue, ref missingValue);
                }

                // release the Word application object
                wdApp.Quit(ref missingValue, ref missingValue, ref missingValue);

                return textsFound;
            }

            // Display usage
            public void usage()
            {
                Console.WriteLine("\nUsage: SearchWordDoc doc_name string_found " +
                    "[start_paragraph_NO.]\n\t\t     [end_paragraph_NO.]");

            }

            // Print the result
            public void printText(ArrayList lst)
            {
                if (lst == null)
                {
                    Console.WriteLine("Error: Null ArrayList.\n");
                    return;
                }

                int len = lst.Count;
                for (int i = 0; i < len; ++ i)
                {
                    Console.WriteLine("\t" + lst[i] as string);
                }

                Console.WriteLine("\nThere are {0} records.", len);
            }

            // Function Main
            public static void Main(string[] args)
            {
                ArrayList textsFound = new ArrayList();
                SearchWordDoc sobject = new SearchWordDoc();

                switch (args.Length)
                {
                    case 0:
                    case 1:
                        sobject.usage();
                        break;
                    case 2:
                        textsFound = sobject.swd(args[0], args[1]);
                        Console.WriteLine("Search Result:\n");
                        sobject.printText(textsFound);
                        break;
                    default:
                        sobject.usage();
                        break;
                }
            }
        }
    } // End

           C#对Word的操作和对Excel等的操作方法很相似。具体的对象说明可以参考.NET SDK。


       收藏   分享  
    顶(0)
      




    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2006/2/18 13:13:00
     
     GoogleAdSense
      
      
      等级:大一新生
      文章:1
      积分:50
      门派:无门无派
      院校:未填写
      注册:2007-01-01
    给Google AdSense发送一个短消息 把Google AdSense加入好友 查看Google AdSense的个人资料 搜索Google AdSense在『 Dot NET,C#,ASP,VB 』的所有贴子 访问Google AdSense的主页 引用回复这个贴子 回复这个贴子 查看Google AdSense的博客广告
    2025/7/23 5:40:46

    本主题贴数1,分页: [1]

    管理选项修改tag | 锁定 | 解锁 | 提升 | 删除 | 移动 | 固顶 | 总固顶 | 奖励 | 惩罚 | 发布公告
    W3C Contributing Supporter! W 3 C h i n a ( since 2003 ) 旗 下 站 点
    苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
    109.375ms