利用 Visual C# .NET 使 Word 自动新建文档

简介:

本文分步介绍如何利用 Visual C# .NET 的自动化功能在 Word 中创建新文档。

代码示例

  • 插入包含文本和格式的段落。
  • 浏览和修改文档中的不同范围。
  • 插入表格、设置表格格式并在表格中填充数据。
  • 添加图表。

要利用 Visual C# .NET 的自动化功能创建新的 Word 文档,请执行以下步骤:

  1. 启动 Microsoft Visual Studio .NET。在文件菜单上,单击新建,然后单击项目。在项目类型下,单击 Visual C# 项目,然后单击模板下的 Windows 应用程序。默认情况下会创建 Form1。
  2. 添加对 Microsoft Word 对象库的引用。为此,请按照下列步骤操作:
    1. 项目菜单上,单击添加引用
    2. 在 COM 选项卡上,找到 Microsoft Word 对象库,然后单击选择
    3. 添加引用对话框中单击确定,接受您的选择。如果系统提示您为选定的库生成包装,请单击
  3. 视图菜单上,选择工具箱以显示工具箱,然后向 Form1 添加一个按钮。
  4. 双击 Button1。出现该窗体的代码窗口。
  5. 在代码窗口中,将以下代码
    private void button1_Click(object sender, System.EventArgs e) { }
    
    替换为:
    private void button1_Click(object sender, System.EventArgs e) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc";  //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); //Insert a paragraph at the end of the document. Word.Paragraph oPara2; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.Text = "Heading 2"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //Insert another paragraph. Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //Insert a 3 x 5 table, fill it with data, and make the first row //bold and italic. Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for(r = 1; r <= 3; r++) for(c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //Add some text after the table. Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "And here's another table:"; oPara4.Format.SpaceAfter = 24; oPara4.Range.InsertParagraphAfter(); //Insert a 5 x 2 table, fill it with data, and change the column widths. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; for(r = 1; r <= 5; r++) for(c = 1; c <= 2; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2 oTable.Columns[2].Width = oWord.InchesToPoints(3); //Keep inserting text. When you get to 7 inches from top of the //document, insert a hard page break. object oPos; double dPos = oWord.InchesToPoints(7); oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter(); do { wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.ParagraphFormat.SpaceAfter = 6; wrdRng.InsertAfter("A line of text"); wrdRng.InsertParagraphAfter(); oPos = wrdRng.get_Information (Word.WdInformation.wdVerticalPositionRelativeToPage); } while(dPos >= Convert.ToDouble(oPos)); object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Word.WdBreakType.wdPageBreak; wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertBreak(ref oPageBreak); wrdRng.Collapse(ref oCollapseEnd); wrdRng.InsertAfter("We're now on page 2. Here's my chart:"); wrdRng.InsertParagraphAfter(); //Insert a chart. Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 4; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); //Close this form. this.Close(); }
    
  6. 滚动到代码窗口的顶部。将下面的代码行添加到 using指令列表的末尾:
    using Word = Microsoft.Office.Interop.Word; using System.Reflection;
    
  7. 按 F5 键生成并运行程序。
  8. 单击 Button1,启动 Word 自动化功能并创建文档。

代码执行完成后,检查为您创建的文档。该文档包含两页设置了格式的段落、表格和图表。

使用模板

  • 您可以对整个文档中的对象的格式设置和布局施加更多控制。
  • 可以使用较少的代码创建文档。

通过使用模板,可以精确地调整表格、段落和其他对象在文档中的布局,并可为这些对象添加格式设置。通过使用自动化功能,可以基于包含下面这样的代码的模板创建新文档:

object oTemplate = "c:\\MyTemplate.dot"; oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

在模板中,可以定义书签,这样,自动化客户端就可以在文档的特定位置加入可变文本,如下所示:

object oBookMark = "MyBookmark"; oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";

使用模板的另一个优点在于,您可以创建和存储希望在运行时应用的格式样式,如下所示:

object oStyleName = "MyStyle"; oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);

- 或者 -

object oStyleName = "MyStyle"; oWord.Selection.set_Style(ref oStyleName); 


本文转自黄聪博客园博客,原文链接:http://www.cnblogs.com/huangcong/archive/2010/03/26/1697047.html,如需转载请自行联系原作者
相关文章
|
15天前
|
数据可视化 网络协议 C#
C#/.NET/.NET Core优秀项目和框架2024年3月简报
公众号每月定期推广和分享的C#/.NET/.NET Core优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍、功能特点、使用方式以及部分功能截图等(打不开或者打开GitHub很慢的同学可以优先查看公众号推文,文末一定会附带项目和框架源码地址)。注意:排名不分先后,都是十分优秀的开源项目和框架,每周定期更新分享(欢迎关注公众号:追逐时光者,第一时间获取每周精选分享资讯🔔)。
|
29天前
|
C# 开发工具 数据安全/隐私保护
C# 实现 Word 加盖骑缝章效果
C# 实现 Word 加盖骑缝章效果
|
29天前
|
SQL 安全 API
C# 读取Word表格到DataSet
C# 读取Word表格到DataSet
|
1月前
|
SQL 数据库 C#
C# .NET面试系列十一:数据库SQL查询(附建表语句)
#### 第1题 用一条 SQL 语句 查询出每门课都大于80 分的学生姓名 建表语句: ```sql create table tableA ( name varchar(10), kecheng varchar(10), fenshu int(11) ) DEFAULT CHARSET = 'utf8'; ``` 插入数据 ```sql insert into tableA values ('张三', '语文', 81); insert into tableA values ('张三', '数学', 75); insert into tableA values ('李四',
65 2
C# .NET面试系列十一:数据库SQL查询(附建表语句)
|
1月前
|
开发框架 算法 搜索推荐
C# .NET面试系列九:常见的算法
#### 1. 求质数 ```c# // 判断一个数是否为质数的方法 public static bool IsPrime(int number) { if (number < 2) { return false; } for (int i = 2; i <= Math.Sqrt(number); i++) { if (number % i == 0) { return false; } } return true; } class Progr
58 1
|
1月前
|
并行计算 安全 Java
C# .NET面试系列四:多线程
<h2>多线程 #### 1. 根据线程安全的相关知识,分析以下代码,当调用 test 方法时 i > 10 时是否会引起死锁? 并简要说明理由。 ```c# public void test(int i) { lock(this) { if (i > 10) { i--; test(i); } } } ``` 在给定的代码中,不会发生死锁。死锁通常是由于两个或多个线程互相等待对方释放锁而无法继续执行的情况。在这个代码中,只有一个线程持有锁,且没有其他线程参与,因此不
104 3
|
8天前
|
开发框架 前端开发 JavaScript
采用C#.Net +JavaScript 开发的云LIS系统源码 二级医院应用案例有演示
技术架构:Asp.NET CORE 3.1 MVC + SQLserver + Redis等 开发语言:C# 6.0、JavaScript 前端框架:JQuery、EasyUI、Bootstrap 后端框架:MVC、SQLSugar等 数 据 库:SQLserver 2012
|
29天前
|
存储 SQL 数据库
C# 将 Word 转文本存储到数据库并进行管理
C# 将 Word 转文本存储到数据库并进行管理
|
29天前
|
存储 SQL C#
C# 读取二维数组集合输出到Word预设表格
C# 读取二维数组集合输出到Word预设表格
|
29天前
|
SQL C# 数据库
C# 读取多条数据记录导出到 Word 标签模板
C# 读取多条数据记录导出到 Word 标签模板