- using System;
- using System.Collections.Generic;
- using System.Data;
- using Microsoft.Office.Core;
- using Word;
- namespace ReadXML
- {
- /// <summary>
- /// 对于Word文档操作的类
- /// 通过COM组件来对Word进
- /// 行读取并存储到字符串中
- /// </summary>
- class myWord
- {
- Word.Application app = new Application(); //可以打开word程序
- Word.Document doc = null; //实例化一个word文档
- string temp = "";
- /// <summary>
- /// 打开一个Word文档
- /// </summary>
- /// <param name="fileName">输入参数为文档路径</param>
- public void openWord(object fileName)
- {
- try
- {
- if (app.Documents.Count > 0)
- {
- object unknow = Type.Missing;
- doc = app.ActiveDocument; //激活文档
- app.ActiveDocument.Save();
- app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
- app.Visible = false;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.ReadLine(); //捕获错误并显示
- app = new Word.Application();
- }
- try
- {
- object unknow = Type.Missing;
- app.Visible = true; //是否显示Word程序
- doc=app.Documents.Open(ref fileName,
- ref unknow, ref unknow, ref unknow, ref unknow,
- ref unknow, ref unknow, ref unknow, ref unknow,
- ref unknow, ref unknow, ref unknow, ref unknow,
- ref unknow, ref unknow, ref unknow);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message); //捕获错误并显示
- Console.ReadLine();
- }
- }
- /// <summary>
- /// 根据段落数目读取并存入字符串中
- /// </summary>
- public void readPar()
- {
- try
- {
- int paraCount = doc.Paragraphs.Count; //获取文档段落数目
- string [] test=new string[paraCount]; //新建一个字符串数组保存按照段落格式的doc文档
- string [] test1 = new string[paraCount]; //新建一个字符串数组保存文本内容
- for (int i = 0; i <paraCount; i++)
- {
- test[i] = doc.Paragraphs[i+1].Range.Text.Trim(); //将段落写到字符串数组里面
- }
- foreach (string temp in test)
- {
- if (temp.Length==0 ||temp.EndsWith(":"))
- {
- //不做任何操作
- }
- else
- {
- //所做操作
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.ReadLine();
- }
- }
- /// <summary>
- /// 关闭文档
- /// </summary>
- public void closeFile()
- {
- try
- {
- object unknow = Type.Missing;
- object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
- app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.ReadLine();
- }
- }
- /// <summary>
- /// 退出Word程序
- /// </summary>
- public void quit()
- {
- try
- {
- object unknow = Type.Missing;
- object saveChanges = Word.WdSaveOptions.wdSaveChanges;
- app.Quit(ref saveChanges, ref unknow, ref unknow);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.ReadLine();
- }
- }
- }
- }