使用Microsoft.Office.Interop.Word类库操作wor文档
一.准备工作
首先在工厂中,引用【Microsoft.Office.Interop.Word】,本地安装了world,就能找到这个类库,如下图。Form1系统自动生成的

Form1的界面很简单,就一个按钮

 二 4个完整实例

4个实例,自测过的,都可用,适用很多种情况操作world。完整代码如下

  1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using MSWord = Microsoft.Office.Interop.Word;
11
12 namespace _24_word_and_excel_Operator
13 {
14 public partial class Form1 : Form
15 {
16 object oMissing = System.Reflection.Missing.Value;
17 public Form1()
18 {
19 InitializeComponent();
20 }
21
22 private void button1_Click(object sender, EventArgs e)
23 {
24 //例子1:新建一个word文档,填入自定义的内容
25 Example1();
26
27 //例子2:操作模板的例子
28 Example2();
29
30 //例子3:操作模板的例子,是例子2的一个简单版本
31 Example3();
32
33 //例子4:复杂的例子,操作模板,标签内填值,文档中画表格,表格中填值。文档中填
34 Example4(@"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\测试文档.docx");
35 }
36 /// <summary>
37 /// 新建一个word文档,填入自定义的内容
38 /// </summary>
39 private void Example1()
40 {
41 //创建一个新的Word应用程序对象
42 Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
43 //创建一个新的Word文档对象,就是创建一个空白的文档
44 MSWord.Document doc = wordApp.Documents.Add();
45 // 在新文档中添加内容
46 MSWord.Paragraph paragraph = doc.Paragraphs.Add();
47 paragraph.Range.Text = "Hello, World! This is a sample Word document.";
48
49 // 保存文档,注意:filePath路径要带上文件名
50 string filePath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\Test\test.docx";
51 doc.SaveAs(filePath);
52
53 // 关闭Word应用程序
54 wordApp.Quit();
55 }
56
57 /// <summary>
58 /// 操作模板的例子
59 /// </summary>
60 private void Example2()
61 {
62 // 模板文件路径
63 string templatePath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\测试文档.docx";
64 // 生成的文档保存路径
65 string newDocumentPath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\Test\新文档.docx";
66
67 // 创建Word应用程序对象
68 Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
69
70 // 打开模板文档
71 Microsoft.Office.Interop.Word.Document templateDocument = wordApp.Documents.Open(templatePath);
72
73 // 复制模板文档的内容
74 templateDocument.Content.Copy();
75
76 // 创建一个新的空白文档
77 Microsoft.Office.Interop.Word.Document newDocument = wordApp.Documents.Add();
78
79 // 将复制的内容粘贴到新文档中
80 newDocument.Content.Paste();
81
82 // 修改新文档的内容
83 MSWord.Paragraph paragraph = newDocument.Content.Paragraphs.Add();
84 paragraph.Range.Text = "This is a document generated from a template.";
85
86 // 保存新文档
87 newDocument.SaveAs(newDocumentPath);
88
89 // 关闭模板文档
90 templateDocument.Close();
91
92 // 关闭Word应用程序
93 wordApp.Quit();
94 }
95 /// <summary>
96 /// 操作模板的例子,是例子2的一个简单版本
97 /// </summary>
98 /// <param name="templatePath"></param>
99 /// <param name="outputPath"></param>
100 public void Example3()
101 {
102 string templatePath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\测试文档.docx";
103 string outputPath = @"D:\110 - C#实例集合\100 - 实例集合\24 word and excel Operator\bin\Debug\Test\例子3的文档.docx";
104
105 // 创建Word应用程序对象
106 Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
107 // 打开模板文档
108 MSWord.Document wordDoc = wordApp.Documents.Open(templatePath);
109 {
110 //这里就是要干什么事了,替换文字,添加内容等操作
111 // 替换模板中的文本
112 FindAndReplace(wordDoc, "要替换的文字", "替换后的文字");
113 // 修改新文档的内容
114 MSWord.Paragraph paragraph = wordDoc.Content.Paragraphs.Add();
115 paragraph.Range.Text = "This is a document generated from a template.";
116 }
117
118 // 保存为新文档
119 wordDoc.SaveAs2(outputPath);
120 // 关闭Word应用程序对象
121 wordApp.Quit();
122 }
123
124 private void FindAndReplace(MSWord.Document doc, string findText, string replaceText)
125 {
126 // 将模板设为可编辑
127 doc.Activate();
128
129 // 执行查找和替换操作
130 // 可以使用其他查找和替换方法,例如使用Range对象
131 object findObj = findText;
132 object replaceObj = replaceText;
133 object missingObj = Type.Missing;
134 doc.Content.Find.Execute(ref findObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
135 ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref replaceObj, ref missingObj,
136 ref missingObj, ref missingObj, ref missingObj, ref missingObj);
137 }
138 private void Example4(string strPath)
139 {
140 object oTemplate = strPath;
141 MSWord.Application wordApp = new MSWord.Application();// 创建一个新的Word应用程序对象
142 wordApp.Visible = true;
143 MSWord.Document oDoc = wordApp.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);// 创建一个新的Word文档对象
144
145 //填写标签
146 object[] bookMark = new object[3];
147 bookMark[0] = "Test1";
148 bookMark[1] = "Test2";
149 oDoc.Bookmarks.get_Item(ref bookMark[0]).Range.Text = "第1个标签";
150 oDoc.Bookmarks.get_Item(ref bookMark[1]).Range.Text = "第2个标签";
151
152
153 //定义一个Word中的表格对象
154 oDoc.Paragraphs.Last.Range.Text = "直接接入式(正向电能)";
155
156 object unite = MSWord.WdUnits.wdStory;
157 oDoc.Content.InsertAfter("\n");
158 wordApp.Selection.EndKey(ref unite, ref oMissing);
159 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
160 object WdLine2 = MSWord.WdUnits.wdLine;//换一行;
161 wordApp.Selection.MoveDown(ref WdLine2, 6, ref oMissing);
162
163 int iRow = 5;
164 int iColumn = 3;
165 MSWord.Table table = oDoc.Tables.Add(wordApp.Selection.Range, iRow, iColumn, ref oMissing, ref oMissing);
166 table.Borders.Enable = 1;
167 for (int i = 1; i < iRow + 1; i++)
168 {
169 if (i == 1)
170 {
171 table.Cell(i, 1).Range.Text = "电压(V)";
172 table.Cell(i, 2).Range.Text = "电流(A)";
173 table.Cell(i, 3).Range.Text = "电能误差(%)";
174 }
175 else
176 {
177 table.Cell(i, 1).Range.Text = (i + 1).ToString();
178 table.Cell(i, 2).Range.Text = (i + 2).ToString();
179 table.Cell(i, 3).Range.Text = (i + 3).ToString();
180 }
181 }
182 table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
183
184 //文档最后填写文字
185 oDoc.Paragraphs.Last.Range.Text = "文档最后的位置:\n\r";
186
187 string docname = string.Empty;
188 docname = $"文档名称";
189
190 //弹出保存文件对话框,保存生成的Word
191 SaveFileDialog sfd = new SaveFileDialog
192 {
193 Filter = "Word Document(*.docx)|*.docx",
194 DefaultExt = "Word Document(*.docx)|*.docx",
195 FileName = docname
196 };
197 if (sfd.ShowDialog() == DialogResult.OK)
198 {
199 object filename = sfd.FileName;
200 oDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing,
201 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
202 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
203 ref oMissing, ref oMissing);
204
205 // 关闭Word应用程序对象
206 wordApp.Quit();
207 }
208 }
209 }
210 }

三 代码分析解读 (重点部分)

 例子1:适用的情况是,代码创建一个新的world文档的情况

注意:无论是例子1,例子2,例子3,其中的路径,要填写自己本地的路径。

例子2和例子3:

两个例子都是操作world模板的,例子2代码复杂写,例子3精简写。效果都是一样的。

例子3中,SaveAs2 方法是 SaveAs 方法的扩展版本,支持更多的保存选项和参数。例子3中, wordDoc.SaveAs2(outputPath);中 outputPath是指定要保存文档的完整路径,包括文件名和文件扩展名。效果如下图

例子4:这个例子稍微复杂一下,设计文档中先插入好标签,标签地方填值,文档中画出表格,表格中填值,文档最后追加文档等操作。

模板文档的标签如下图:

例子4的效果如下图:

C#操作Microsoft.Office.Interop.Word类库完整例子的更多相关文章

  1. (转)无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。此操作失败的原因是对 IID 为“{00020970-

    HRESULT:0x80030002 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft ...

  2. 关于.net Microsoft.Office.Interop.Word组建操作word的问题,如何控制word表格单元格内部段落的样式。

    控制word表格单元格内部文字样式.我要将数据导出到word当中,对于word表格一个单元格中的一段文字,要设置不同的样式,比如第一行文字作为标题要居中,加粗,第二行为正常的正文. 代码如下 publ ...

  3. 调用Microsoft.Office.Interop.Word生成自定义Word文档

    具体思路: 1.先制作Word模版,使用文本框+书签的方式来设计模版: 2.模版制作完之后,根据模版生成新文件,使用File.Copy方法,生成.doc格式新文件: 3.后台取得数据,参照网页渲染的方 ...

  4. 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。

    无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Wor ...

  5. System.InvalidCastException: 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接口类型“Microsoft.Office.Interop.Word._Application”。

    报错:System.InvalidCastException: 无法将类型为“Microsoft.Office.Interop.Word.ApplicationClass”的 COM 对象强制转换为接 ...

  6. C#用Microsoft.Office.Interop.Word进行Word转PDF的问题

    之前用Aspose.Word进行Word转PDF发现'\'这个字符会被转换成'¥'这样的错误,没办法只能换个方法了.下面是Microsoft.Office.Interop.Word转PDF的方法: p ...

  7. Microsoft.Office.Interop.Word 创建word

    Microsoft.Office.Interop.Word 创建word 转载:http://www.cnblogs.com/chenbg2001/archive/2010/03/14/1685746 ...

  8. VS编程中找不到Microsoft.Office.Core、Microsoft.Office.Interop.Word和VBIDE

    在使用vs2005. vs2008. vs2010 制作包含 word等office的应用程序时,有时找不到对Microsoft.Office.Core. Microsoft.Office.Inter ...

  9. C#引用Office.word出错的解决办法-无法嵌入互操作类型“Microsoft.Office.Interop.Word.ApplicationClass” 【转】

    本文章转自 suchso 1.系统找不到 Microsoft.Office.Interop.Word" "Could not load file or assembly 'Micr ...

  10. 无法嵌入互操作类型“Microsoft.Office.Interop.Word.ApplicationClass”。请改用适用的接口。

    引用里找到Microsoft.Office.Interop.Word右键属性 在嵌入互操作类型里,选上False就行了.

随机推荐

  1. ITIL4与Devops(一)

    目录 一.服务管理与ITIL 1.1 服务管理现状 1.2 服务管理原则 1.3 ITIL版本发展历程 ITIL2 服务支持 服务交付 服务战略 ITIL3 框架 职能 ITIL 2011 流程的基本 ...

  2. python数据处理:获取Dataframe中的一列或一行

    解决方案 df['w'] #选择表格中的'w'列,使用类字典属性,返回的是Series类型 df.w #选择表格中的'w'列,使用点属性,返回的是Series类型 df[['w']] #选择表格中的' ...

  3. Prompt Playground 7月开发记录(2): Avalonia 应用开发

    Prompt Playground 7月开发记录(2): Avalonia 应用开发 仅以此文记录开发过程中遇到的问题和个人的解决方案,如若有理解偏差或者更好的解决方案,欢迎指正. 客户端的开发的确不 ...

  4. mysql拓展

    事务定义 就是将一组SQL语句放在同一批次内去执行 如果一个sql语句出错,则改批次内的所有sql都将被取消执行 (1)原子性 一个事务要么全部提交成功,要么全部失败回滚,不能只执行其中的一部分操作, ...

  5. JVM性能监控和调优

    JVM性能监控和调优 JVM(Java虚拟机)调优是为了优化Java应用程序的性能和稳定性.JVM调优的目的是通过调整JVM的配置参数和优化应用程序代码,使其在给定的硬件和软件环境下达到更好的性能表现 ...

  6. 优化 Redis 集群缓存分配:解决节点间分配不均导致内存溢出问题

    一.Redis 集群部署简介 在现代应用程序中,缓存被广泛应用以提高性能和减轻后端数据库的压力.本文将探讨面对 Redis 集群缓存分配不均问题时的解决方法. 我们的 Redis 集群部署包括 3 主 ...

  7. 带你读论文丨S&P2019 HOLMES Real-time APT Detection

    本文分享自华为云社区<[论文阅读] (09)S&P2019 HOLMES Real-time APT Detection(溯源图)>,作者: eastmount . 摘要 本文提出 ...

  8. 组合查询(left_inner_right)与排序(order by _DESC _ASC)在题目中的应用

    1,想要让哪一列放在开头或者结尾,只需要将select中的查询位置放在最开始或者结尾即可: 2,组合查询要注意使用 on 加上组合条件: 3,order by 默认升序(ASC),降序使用:order ...

  9. 质量管理 | QC、QA、QM,去QA化与降本增效

    现在国内职业的质量管理都是从 CMMI 和 ISO 质量体系演化过来的,但是能做真正的质量管理的公司很少.质量管理的 QC 偏测试,对最终的产品负责:QA 偏过程,从过程把控质量:QM 偏体系,类似于 ...

  10. word2010中统一调整表格格式

    word中统一调整表格格式基本思路是: 1.选中所有的表格. 2.再对表格格式调整.    选中所有表格需要用到宏,操作很简单,具体操作如下: (1)工具栏"视图"下右下角&quo ...