Office API的示例
最近在做一个使用WSS开发公司文档管理系统的项目,文档管理方面的需求已经谈得七七八八了。
里面涉及到保护Word 模板的需求,决定使用 Office API来开发。
经过询问微软MCS几位人士,有的说可以用在Web Application 中,有的说不能用。唉,不知道听谁的。
不管怎么样,代码样例已经出来了。
由于是样例,没有什么错误处理和类的封装,因为我很清楚知道,不把这些放在一个可用的类中是无法使用Office API的,听过太多的血与泪的故事了。
1
using System;2
using System.Drawing;3
using System.Collections;4
using System.ComponentModel;5
using System.Windows.Forms;6
using System.Data;7
using Microsoft.Office.Core;8
using Word = Microsoft.Office.Interop.Word;9
using System.Reflection;10

11

12
namespace WindowsApplication213


{14

/**//// <summary>15
/// Form1 的摘要说明。16
/// </summary>17
public class Form1 : System.Windows.Forms.Form18

{19

20
private Word.Application _wordApp = null;21
private Word.Document doc = null;22
private System.Windows.Forms.Button button1;23
private System.Windows.Forms.Button button2;24
private System.Windows.Forms.Button button3;25
private System.Windows.Forms.ToolTip toolTip1;26
private System.Windows.Forms.Panel panel1;27
private System.Windows.Forms.Panel panel2;28
private System.Windows.Forms.Panel panel3;29
private System.Windows.Forms.Label label1;30
private System.Windows.Forms.Label label2;31
private System.Windows.Forms.Label label3;32
private System.Windows.Forms.Panel panel4;33
private System.Windows.Forms.Button button4;34
private System.Windows.Forms.OpenFileDialog openFileDialog1;35
private System.Windows.Forms.Label label4;36
private System.Windows.Forms.Panel panel5;37
private System.Windows.Forms.Button button5;38
private System.Windows.Forms.Label label5;39
private System.ComponentModel.IContainer components;40

41
public Form1()42

{43
//44
// Windows 窗体设计器支持所必需的45
//46
InitializeComponent();47

48
//49
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码50
//51
}52

53

/**//// <summary>54
/// 清理所有正在使用的资源。55
/// </summary>56
protected override void Dispose( bool disposing )57

{58
if( disposing )59

{60
if (components != null) 61

{62
components.Dispose();63
}64
}65
base.Dispose( disposing );66
}67

68

Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码69

/**//// <summary>70
/// 设计器支持所需的方法 - 不要使用代码编辑器修改71
/// 此方法的内容。72
/// </summary>73
private void InitializeComponent()74

{75
this.components = new System.ComponentModel.Container();76
this.button1 = new System.Windows.Forms.Button();77
this.button2 = new System.Windows.Forms.Button();78
this.button3 = new System.Windows.Forms.Button();79
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);80
this.panel1 = new System.Windows.Forms.Panel();81
this.panel2 = new System.Windows.Forms.Panel();82
this.panel3 = new System.Windows.Forms.Panel();83
this.label1 = new System.Windows.Forms.Label();84
this.label2 = new System.Windows.Forms.Label();85
this.label3 = new System.Windows.Forms.Label();86
this.panel4 = new System.Windows.Forms.Panel();87
this.button4 = new System.Windows.Forms.Button();88
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();89
this.label4 = new System.Windows.Forms.Label();90
this.panel5 = new System.Windows.Forms.Panel();91
this.button5 = new System.Windows.Forms.Button();92
this.label5 = new System.Windows.Forms.Label();93
this.panel1.SuspendLayout();94
this.panel2.SuspendLayout();95
this.panel3.SuspendLayout();96
this.panel4.SuspendLayout();97
this.panel5.SuspendLayout();98
this.SuspendLayout();99
// 100
// button1101
// 102
this.button1.Location = new System.Drawing.Point(8, 8);103
this.button1.Name = "button1";104
this.button1.TabIndex = 0;105
this.button1.Text = "创建";106
this.button1.Click += new System.EventHandler(this.button1_Click);107
// 108
// button2109
// 110
this.button2.Location = new System.Drawing.Point(8, 8);111
this.button2.Name = "button2";112
this.button2.TabIndex = 1;113
this.button2.Text = "保存并关闭";114
this.button2.Click += new System.EventHandler(this.button2_Click);115
// 116
// button3117
// 118
this.button3.Location = new System.Drawing.Point(8, 8);119
this.button3.Name = "button3";120
this.button3.Size = new System.Drawing.Size(88, 23);121
this.button3.TabIndex = 2;122
this.button3.Text = "取BookMark值";123
this.button3.Click += new System.EventHandler(this.button3_Click);124
// 125
// panel1126
// 127
this.panel1.Controls.Add(this.label1);128
this.panel1.Controls.Add(this.button1);129
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;130
this.panel1.Location = new System.Drawing.Point(0, 0);131
this.panel1.Name = "panel1";132
this.panel1.Size = new System.Drawing.Size(344, 40);133
this.panel1.TabIndex = 3;134
// 135
// panel2136
// 137
this.panel2.Controls.Add(this.label2);138
this.panel2.Controls.Add(this.button2);139
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;140
this.panel2.Location = new System.Drawing.Point(0, 40);141
this.panel2.Name = "panel2";142
this.panel2.Size = new System.Drawing.Size(344, 36);143
this.panel2.TabIndex = 4;144
// 145
// panel3146
// 147
this.panel3.Controls.Add(this.label3);148
this.panel3.Controls.Add(this.button3);149
this.panel3.Dock = System.Windows.Forms.DockStyle.Top;150
this.panel3.Location = new System.Drawing.Point(0, 76);151
this.panel3.Name = "panel3";152
this.panel3.Size = new System.Drawing.Size(344, 36);153
this.panel3.TabIndex = 5;154
// 155
// label1156
// 157
this.label1.Location = new System.Drawing.Point(108, 8);158
this.label1.Name = "label1";159
this.label1.Size = new System.Drawing.Size(228, 23);160
this.label1.TabIndex = 1;161
this.label1.Text = "演示打开Word并新增一个Document";162
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;163
// 164
// label2165
// 166
this.label2.Location = new System.Drawing.Point(108, 7);167
this.label2.Name = "label2";168
this.label2.Size = new System.Drawing.Size(228, 23);169
this.label2.TabIndex = 2;170
this.label2.Text = "演示保存打开的Word并自动加入文档保护";171
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;172
// 173
// label3174
// 175
this.label3.Location = new System.Drawing.Point(108, 7);176
this.label3.Name = "label3";177
this.label3.Size = new System.Drawing.Size(228, 23);178
this.label3.TabIndex = 3;179
this.label3.Text = "演示取得Word文档中所有BookMark并显示";180
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;181
this.label3.Click += new System.EventHandler(this.label3_Click);182
// 183
// panel4184
// 185
this.panel4.Controls.Add(this.label4);186
this.panel4.Controls.Add(this.button4);187
this.panel4.Dock = System.Windows.Forms.DockStyle.Top;188
this.panel4.Location = new System.Drawing.Point(0, 112);189
this.panel4.Name = "panel4";190
this.panel4.Size = new System.Drawing.Size(344, 48);191
this.panel4.TabIndex = 6;192
// 193
// button4194
// 195
this.button4.Location = new System.Drawing.Point(8, 12);196
this.button4.Name = "button4";197
this.button4.TabIndex = 0;198
this.button4.Text = "保护文档";199
this.button4.Click += new System.EventHandler(this.button4_Click);200
// 201
// label4202
// 203
this.label4.Location = new System.Drawing.Point(108, 12);204
this.label4.Name = "label4";205
this.label4.Size = new System.Drawing.Size(228, 23);206
this.label4.TabIndex = 1;207
this.label4.Text = "演示保护文档的不可编辑内容";208
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;209
// 210
// panel5211
// 212
this.panel5.Controls.Add(this.label5);213
this.panel5.Controls.Add(this.button5);214
this.panel5.Dock = System.Windows.Forms.DockStyle.Top;215
this.panel5.Location = new System.Drawing.Point(0, 160);216
this.panel5.Name = "panel5";217
this.panel5.Size = new System.Drawing.Size(344, 100);218
this.panel5.TabIndex = 7;219
// 220
// button5221
// 222
this.button5.Location = new System.Drawing.Point(8, 16);223
this.button5.Name = "button5";224
this.button5.TabIndex = 1;225
this.button5.Text = "取消保护";226
this.button5.Click += new System.EventHandler(this.button5_Click);227
// 228
// label5229
// 230
this.label5.Location = new System.Drawing.Point(108, 16);231
this.label5.Name = "label5";232
this.label5.Size = new System.Drawing.Size(228, 23);233
this.label5.TabIndex = 2;234
this.label5.Text = "演示取消保护文档";235
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;236
// 237
// Form1238
// 239
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);240
this.ClientSize = new System.Drawing.Size(344, 217);241
this.Controls.Add(this.panel5);242
this.Controls.Add(this.panel4);243
this.Controls.Add(this.panel3);244
this.Controls.Add(this.panel2);245
this.Controls.Add(this.panel1);246
this.MaximizeBox = false;247
this.MinimizeBox = false;248
this.Name = "Form1";249
this.Text = "保护模板功能演示";250
this.Load += new System.EventHandler(this.Form1_Load);251
this.panel1.ResumeLayout(false);252
this.panel2.ResumeLayout(false);253
this.panel3.ResumeLayout(false);254
this.panel4.ResumeLayout(false);255
this.panel5.ResumeLayout(false);256
this.ResumeLayout(false);257

258
}259
#endregion260

261

/**//// <summary>262
/// 应用程序的主入口点。263
/// </summary>264
[STAThread]265
static void Main() 266

{267
Application.Run(new Form1());268
}269

270
private void Form1_Load(object sender, System.EventArgs e)271

{272
// Word.Application oWord;273
// Word._Document oDoc;274
// object oMissing = Missing.Value;275
// object oDocBuiltInProps;276
// object oDocCustomProps;277
// 278
// //Create an instance of Microsoft Word and make it visible.279
// oWord = new Word.Application();280
// oWord.Visible = true;281
//282
// //Create a new Document and get the BuiltInDocumentProperties collection.283
// oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, 284
// ref oMissing);285
// oDocBuiltInProps = oDoc.BuiltInDocumentProperties;286
// Type typeDocBuiltInProps = oDocBuiltInProps.GetType();287
// //Get the Author property and display it.288
// string strIndex = "Author";289
// string strValue;290
// object oDocAuthorProp = typeDocBuiltInProps.InvokeMember("Item", 291
// BindingFlags.Default | 292
// BindingFlags.GetProperty, 293
// null,oDocBuiltInProps, 294
// new object[] {strIndex} );295
// Type typeDocAuthorProp = oDocAuthorProp.GetType();296
// strValue = typeDocAuthorProp.InvokeMember("Value", 297
// BindingFlags.Default |298
// BindingFlags.GetProperty,299
// null,oDocAuthorProp,300
// new object[] {} ).ToString();301
// MessageBox.Show( "The Author is: " + strValue,"Author" );302
//303
// //Set the Subject property.304
// strIndex = "Subject";305
// strValue = "The Subject";306
// typeDocAuthorProp.InvokeMember("Item", 307
// BindingFlags.Default | 308
// BindingFlags.SetProperty, 309
// null,oDocBuiltInProps, 310
// new object[] {strIndex,strValue} );311
// 312
// //Add a property/value pair to the CustomDocumentProperties collection.313
// oDocCustomProps = oDoc.CustomDocumentProperties;314
// Type typeDocCustomProps = oDocCustomProps.GetType();315
//316
// strIndex = "Knowledge Base Article";317
// strValue = "Q303296";318
// object[] oArgs = {strIndex,false,319
// MsoDocProperties.msoPropertyTypeString,320
// strValue};321
//322
// typeDocCustomProps.InvokeMember("Add",BindingFlags.Default | 323
// BindingFlags.InvokeMethod, null, 324
// oDocCustomProps, oArgs );325
//326
// MessageBox.Show("Select \"Properties\" from the File menu "327
// + "to view the changes.\nSelect the Summary tab to view "328
// + "the Subject property and the Custom tab to view the Knowledge" 329
// + "Base Article property.", "Check File Properties",330
// MessageBoxButtons.OK,MessageBoxIcon.Information);331
// 332
333
}334

335
private void button1_Click(object sender, System.EventArgs e)336

{337
//演示打开Word并新增一个Document338
Object missing = Type.Missing;339

340
_wordApp = new Word.Application();341
_wordApp.Visible = true;342
Word.Documents docs = _wordApp.Documents;343
doc = docs.Add(ref missing, ref missing, ref missing, ref missing);344

345
}346

347
private void button2_Click(object sender, System.EventArgs e)348

{349
Object missing = Type.Missing;350
Object sFileName = "C:\\Sample.doc";351
object password = "123456";352
object noreset = true;353
//判断用户是否加入了任何密码,如果加入了则不能保存到系统中354
if(doc.HasPassword)355

{356
MessageBox.Show("文档在保存到系统前不能设置密码!");357
return;358
}359

360
//添加保护361
doc.Protect(Word.WdProtectionType.wdAllowOnlyComments,ref noreset,ref password,ref missing,ref noreset);362
//保存363
doc.SaveAs(ref sFileName, ref missing, ref missing, 364
ref missing, ref missing, ref missing, ref missing, 365
ref missing, ref missing, ref missing, ref missing, 366
ref missing, ref missing, ref missing, ref missing, 367
ref missing);368

369
doc.Close(ref missing, ref missing, ref missing);370

371
_wordApp.Quit(ref missing, ref missing, ref missing);372

373
_wordApp = null;374

375
376
GC.Collect();377

378
GC.WaitForPendingFinalizers();379

380
GC.Collect();381

382
GC.WaitForPendingFinalizers();383
}384

385
private void button3_Click(object sender, System.EventArgs e)386

{387
Object missing = Type.Missing;388

389
//创建一个Word.Application对象(是每个Office对象(如Word\Excel\Power Point等)的根)390
_wordApp = new Word.Application();391

392
object fileName = "c:\\Sample.doc";393
//默认不显示Word界面,如果想看一下界面,你可以把这一句起用。394
//_wordApp.Visible = true;395
//打开一个Word文档396
doc = _wordApp.Documents.Open(ref fileName,ref missing,ref missing,397
ref missing,ref missing,ref missing,ref missing,ref missing,398
ref missing,ref missing,ref missing,ref missing,399
ref missing,ref missing,ref missing,ref missing);400

401
//获取文档中的每一个BookMark402
System.Text.StringBuilder stringbuilder = new System.Text.StringBuilder();403
stringbuilder.Append("当前文档中的书签如下:\r\n");404
foreach(Word.Bookmark bookmark in doc.Bookmarks )405

{406
stringbuilder.Append("书签名:" + bookmark.Name + "\b\b 值=" + bookmark.Range.Text+"\r\n");407
}408

409
MessageBox.Show(stringbuilder.ToString());410
//关闭文档411
doc.Close(ref missing, ref missing, ref missing);412
//退出Word App413
_wordApp.Quit(ref missing, ref missing, ref missing);414
_wordApp = null;415
//调用GC(垃圾收集器进行回收,防止Word仍然驻留在内存中416
GC.Collect();417
GC.WaitForPendingFinalizers();418
//保险起见,再回收一次419
GC.Collect();420
GC.WaitForPendingFinalizers();421
}422

423
private void label3_Click(object sender, System.EventArgs e)424

{425
426
}427

428
private void button4_Click(object sender, System.EventArgs e)429

{430
if(this.openFileDialog1.ShowDialog() == DialogResult.OK)431

{432
Object missing = Type.Missing;433
Object sFileName = this.openFileDialog1.FileName;434

435

436
object password = "123456";437
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();438
byte[] hashedBytes = md5.ComputeHash(new System.Text.UTF8Encoding().GetBytes(password.ToString()));439
password = hashedBytes.ToString();440
object noreset = true;441
//创建一个Word.Application对象(是每个Office对象(如Word\Excel\Power Point等)的根)442
_wordApp = new Word.Application();443
try444

{445
doc = _wordApp.Documents.Open(ref sFileName,ref missing,ref missing,446
ref missing,ref missing,ref missing,ref missing,ref missing,447
ref missing,ref missing,ref missing,ref missing,448
ref missing,ref missing,ref missing,ref missing);449

450
//判断用户是否加入了任何密码,如果加入了则不能保存到系统中451
if(doc.HasPassword)452

{453
MessageBox.Show("文档在保存到系统前不能设置密码!");454
return;455
}456

457
if(doc.ProtectionType != Word.WdProtectionType.wdNoProtection)458

{459
MessageBox.Show("文档已启用保护时,系统无法再进行保护,必须移除保护密码");460
Form2 frm = new Form2();461
if(frm.ShowDialog() == DialogResult.Cancel) return;462
object pass = frm.Password;463
doc.Unprotect(ref pass);464
}465

466

467
//添加保护468
doc.Protect(Word.WdProtectionType.wdAllowOnlyComments,ref noreset,ref password,ref missing,ref noreset);469
//保存470
doc.Save();471

472
doc.Close(ref missing, ref missing, ref missing);473
MessageBox.Show("文档已被保护,保护密码是:123456");474
}475
finally476

{477
_wordApp.Quit(ref missing, ref missing, ref missing);478

479
_wordApp = null; 480
GC.Collect();481
GC.WaitForPendingFinalizers();482
GC.Collect();483
GC.WaitForPendingFinalizers();484
}485
}486
487
}488

489
private void button5_Click(object sender, System.EventArgs e)490

{491
if(this.openFileDialog1.ShowDialog() != DialogResult.OK) return;492

493
Object missing = Type.Missing;494
Object sFileName = this.openFileDialog1.FileName;495

496
object password = "123456";497
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();498
byte[] hashedBytes = md5.ComputeHash(new System.Text.UTF8Encoding().GetBytes(password.ToString()));499
password = hashedBytes.ToString();500
object noreset = true;501
//创建一个Word.Application对象(是每个Office对象(如Word\Excel\Power Point等)的根)502
_wordApp = new Word.Application();503
try504

{505
doc = _wordApp.Documents.Open(ref sFileName,ref missing,ref missing,506
ref missing,ref missing,ref missing,ref missing,ref missing,507
ref missing,ref missing,ref missing,ref missing,508
ref missing,ref missing,ref missing,ref missing);509

510
//判断用户是否加入了任何密码,如果加入了则不能保存到系统中511
if(doc.HasPassword)512

{513
MessageBox.Show("文档在保存到系统前不能设置密码!");514
return;515
}516

517
if(doc.ProtectionType == Word.WdProtectionType.wdNoProtection)518

{519
MessageBox.Show("文档未启用保护");520
return;521
}522

523
//取消保护524
doc.Unprotect(ref password);525
526
//保存527
doc.Save();528

529
doc.Close(ref missing, ref missing, ref missing);530
MessageBox.Show("文档已取消保护");531
}532
finally533

{534
_wordApp.Quit(ref missing, ref missing, ref missing);535

536
_wordApp = null; 537
GC.Collect();538
GC.WaitForPendingFinalizers();539
GC.Collect();540
GC.WaitForPendingFinalizers();541
} 542
}543
}544
}545

posted on 2005-12-08 19:18 软件之美,美在缺陷-Johnson 阅读(2688) 评论(0) 收藏 举报
浙公网安备 33010602011771号