C# 拆分word(根据标题或书签拆分) (转自zrx401558287)

转自:http://www.cnblogs.com/zrx401558287/archive/2009/03/19/1404606.html

 

C# 拆分word(根据标题或书签拆分)

【实现功能】

     读取word文件的内容,根据word的标题或书签把word分成多个部分的word文件。

【开发环境】

     vs2005+office2003

【实现过程】

     1:操作word文档首先要添加word的.NET引用:Microsoft.Office.Interop.Word

     2:首先读取word文档


        ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();

        
/// <summary>
        
/// 读取word文档
        
/// </summary>
        
/// <param name="path">word文档路径</param>
        
/// <returns></returns>

        private Document ReadDocument(string path)
        
{
            
object missing = System.Reflection.Missing.Value;
            
            Type wordType 
= word.GetType();

            Documents docs 
= word.Documents;
            Type docsType 
= docs.GetType();
            
object objDocName = path;
            Document doc 
= (Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, truetrue });

            
return doc;
        }

 

     3:创建一个文档来保存拆分的word部分


        /// <summary>
        
/// 创建word文档
        
/// </summary>
        
/// <returns></returns>

        private Document CreateDocument()
        
{
            
object missing = System.Reflection.Missing.Value;
            Document newdoc 
= word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            
return newdoc;
        }

 

     4:比较关键的就是根据标题或书签来定位了.

     如果根据标题定位就比较慢了,我们要遍历word中所有的Paragraphs然后判断他的OutlineLevel是否是标题,如果他的值是WdOutlineLevel.wdOutlineLevel1则说明是标题1,这样以此类推.

     如果根据书签来定位就是比较简单的也是比较有效率的,因为word对象里本身就有Bookmarks这个对象,我的程序里是固定的书签所以我就直接根据定义了一个int[,] result = new int[9, 2];来记录这九个书签的开始和结束位置.


/// <summary>
        
/// 获取书签的位置
        
/// </summary>
        
/// <param name="word">文档对象</param>
        
/// <returns></returns>

        private int[,] GetPosition(Document word)
        
{
            
int[,] result = new int[92];
            
int titleIndex = 0;
            
int bmcount = word.Bookmarks.Count;
            
for (int i = 1; i <= bmcount; i++)
            
{
                
object index = i;
                Bookmark bm
=word.Bookmarks.get_Item(ref index);
                
if (bm.Name == "模板书签禁止修改" + Convert.ToString(titleIndex + 1))
                
{
                    result[titleIndex, 
0= bm.Start;
                    result[titleIndex, 
1= bm.End;
                    titleIndex
++;
                }

            }

            
return result;
        }

     

     5:最后只需要根据定位把内容copy到新的word文档中然后保存就行了.

     word中可以使用Range方法,只需要传递开始和结束位置就可以返回一个Range对象,而这个对象就有copy的方法,我们把range copy到剪贴板中,然后在新建的文档中调用Paste方法然后再保存就成功把这部分提取到一个新的word中了。

 

Code

 

【结语】

     开始我用的遍历paragraph但对于大一点的文档超费时间,所以改成根据bookmark来定位。

     这个只是简单的操作word的一个例子,希望对大家有所帮助。

【完整源码】https://files.cnblogs.com/zrx401558287/splitword.rar

 

posted @ 2009-05-21 15:59  Candyxiaoqiang  阅读(997)  评论(0编辑  收藏  举报