分享
 
 
 

Automating MS Word Using Visual Studio .NET(收藏)

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

Introduction

One day you may be asked to write a parser that will have to parse a bunch of documents and break them down into a structured model and store them in a relational-database. And those documents will most likely be written in MS Word. And the sad part would be that they would not have any structure, they will not follow any standard and they will include OLE/embedded objects. I was assigned with such a task, and it was a very interesting experience for me.

Since this was my first such project, meaning automating MS Office application, I had to go and do a lot of reading about automation. The good news is that there is a bunch of stuff out there; the bad news is that all of them are written for VB or VBA developers. I couldn’t find anything for C++ developers. Long story short, I am writing this article to make things a little easier for someone else that might be assigned with a similar task.

The original code I worked on was written using Borland C++ Builder 5 Professional. This article is however, the C# version. By the way if you are interested in seeing the C++ version ask for it and I will post it. I encourage people to take a look at the C++ version sometime to start appreciate the simplicity of C#.

Background

No special background is necessary. Just have some hands on experience with C#.

Using the code

I am going to include some code that will allow you to understand how to get what you need from a Word document. It really doesn’t matter if you are making a console application or a Windows application. The steps and the code is the same. So you can go ahead and create new C# project. You may choose to create a Windows Application that way you can click some button.

Okay so once you create a new project, go ahead and right click on References in the Solution Explorer, and select Add Reference… When the Add Reference window comes up select the COM tab. This will list all Component Names which are available on your machine, since we are going to use MS Word, we will scroll down until we find: Microsoft Word 9.0 Object Library.

Note: Yours might be a different version depending on the version of Office installed on your machine. This is for MS Word 2000.

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace sparser

{

/// Summary description for Form1.

public class frmParserMainUI : System.Windows.Forms.Form

{

/// User Interface Objects

/// I have removed the user interface object, since

/// they have nothing to do with

/// the actual code, and they take a lot of space.

...

/// Required designer variable.

private System.ComponentModel.Container components = null;

private System.Windows.Forms.OpenFileDialog openFileDialog;

...

The following block create MS Word COM Object. This is the object which will be used to access WORD application functions. To see what functions are available you can do it either within Visual Studio .NET IDE or MS Word.

/// MS Word COM Object

/// This is where we create our WORD object

private Word.ApplicationClass vk_word_app = new Word.ApplicationClass();

...

To view the functions from MS Word, launch Word, hold down the Alt key and press F11 [Alt+F11], this will give you the VBA window, once there press F1 to get the help window, and do a search for document object. This is the best source of documentation for available functions. However, the documents have been written for VBA, but at least you know what the function does and what kind of parameters it takes.

Alright the code continued...

...

/// The main entry point for the application.

[STAThread]

static void Main()

{

Application.Run(new frmParserMainUI());

}

/// Get source document. Open a FileDialog window for

/// user to select single/multiple files for

/// parsing.

private void butSourceDocument_Click(object sender, System.EventArgs e)

{

if( openFileDialog.ShowDialog() == DialogResult.OK )

{

object fileName = openFileDialog.FileName;

object saveFile = fileName + "_Vk.doc";

object vk_read_only = false;

object vk_visible = true;

object vk_false = false;

object vk_true = true;

object vk_dynamic = 2;

object vk_missing = System.Reflection.Missing.Value;

// Let make the word application visible

vk_word_app.Visible = true;

vk_word_app.Activate();

// Let's open the document

Word.Document vk_my_doc = vk_word_app.Documents.Open(

ref fileName, ref vk_missing, ref vk_read_only,

ref vk_missing, ref vk_missing,

ref vk_missing, ref vk_missing, ref vk_missing, ref vk_missing,

ref vk_missing, ref vk_missing, ref vk_visible );

...

Alright, so here the user is given a file open dialog where they can select a Word document. Notice that we save the filename as an object. This is because the functions that we use need reference to object.

So now we can use our Word object to start Word. This is achieved by the vk_word_app.Visible = true; and vk_word_app.Activate(); The first statement makes sure that the instance of Word is visible, and the second one activate it. If you don't want the Word instance to be visible just set the Visible property to false.

Next we create a Word Document object, and that is done using Word.Document vk_my_doc = vk_word_app.Documents.Open( ... ); Notice all the parameters which are required by the function. Most of them are NULL values, so we use vk_missing which is a System.Reflection.Missing.Value.

So now we have created a Word instance and opened a Word document. Now let's move on with the code...

...

// Let's create a new document

Word.Document vk_new_doc = vk_word_app.Documents.Add(

ref vk_missing, ref vk_missing, ref vk_missing, ref vk_visible );

// Select and Copy from the original document

vk_my_doc.Select();

vk_word_app.Selection.Copy();

// Paste into new document as unformatted text

vk_new_doc.Select();

vk_word_app.Selection.PasteSpecial( ref vk_missing, ref vk_false,

ref vk_missing, ref vk_false, ref vk_dynamic,

ref vk_missing, ref vk_missing );

// close the original document

vk_my_doc.Close( ref vk_false, ref vk_missing, ref vk_missing );

...

Next we would like to create a new document. This is just like clicking the New Blank Document button on the toolbar. So we create another Word Document object, and this time notice that we use vk_word_app.Documents.Add( ... ); This will add a new blank document which is also visible.

Next what we do is select all content from the document which we opened, and we copy it.

Next we paste our content into the new document with a special format. The format used in the code is for plain text. This is because we want to get rid of the crap Word puts into the formatting of the text. Then we close our original document without making any changes.

...

vk_new_doc.Select();

FindAndReplace( "^t^t^t^t^t^t^t", "^t", vk_num );

// Save the new document

vk_new_doc.SaveAs( ref saveFile, ref vk_missing,

ref vk_missing, ref vk_missing, ref vk_missing,

ref vk_missing, ref vk_missing, ref vk_missing,

ref vk_missing, ref vk_missing, ref vk_missing );

// close the new document

vk_new_doc.Close( ref vk_false, ref vk_missing, ref vk_missing );

// close word application

vk_word_app.Quit( ref vk_false, ref vk_missing, ref vk_missing );

}

}

...

Now let's say if we are interested in doing a find and replace operation, we would basically select the whole document and use the Find and Replace function.

Note: The FindAndReplace function does not belong to Word object or Document object, it is user defined, the actual Find and Replace function is define in the following block.

Next we want to save our changes to the new document and close it.

And finally quit word.

...

private void FindAndReplace( object vk_find, object vk_replace,

object vk_num )

{

object vk_read_only = false;

object vk_visible = true;

object vk_false = false;

object vk_true = true;

object vk_dynamic = 2;

vk_word_app.Selection.Find.Execute( ref vk_find,

ref vk_false, ref vk_false,

ref vk_false, ref vk_false, ref vk_false, ref vk_true,

ref vk_num, ref vk_false,

ref vk_replace, ref vk_dynamic, ref vk_false,

ref vk_false, ref vk_false, ref vk_false );

}

}

}

The above block shows the actual FindAndReplace function. Notice that it belongs to the vk_word_app object. And the function operates on the active selection. The Find and Replace function is a part of the Find function with special parameters. These parameters can be identified in the documentation as I mentioned at the top of the article.

The code demonstrated above, illustrates how to open a word document, how to create a new word document, selecting, copying, pasting, and doing a Find and Replace function.

As you can see, once you get an understanding of how Word operates and go through the documentation you will be able to automate all the functions that Word has to provide.

// Let's get the content from the document

Word.Paragraphs vk_my_doc_p = vk_new_doc.Paragraphs;

// Count number of paragraphs in the file

long p_count = vk_my_doc_p.Count;

// step through the paragraphs

for( int i=1; i<=p_count; i++ )

{

Word.Paragraph vk_p = vk_my_doc_p.Item( i );

Word.Range vk_r = vk_p.Range;

string text = vk_r.Text;

MessageBox.Show( text );

}

If you take a look at the code above, you can see that we have declared an object that represents a paragraph in a Word document. This is how you can extract text from a Word document, you get the paragraph object and you can access all the paragraphs that are contained in the list. The code loops thru every paragraph of a given document and displays them in a MessageBox.

Points of Interest

The new version of Office, Office 2003 is going to make things a little easier for Office developers. So if you are an Office developer, you should start looking into the features that Office 2003 has to offer. One of the nice features that I like is the capability of exporting documents into XML format.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有