在前几篇文章中,我们学习了Word对象模型的基础知识、文本操作与格式设置等内容。掌握了这些基础知识后,我们现在可以进一步深入到文档的结构化元素操作,包括段落与节的管理、表格的创建与操作以及图片的插入等。
本文将详细介绍如何使用MudTools.OfficeInterop.Word库来操作Word文档中的结构化元素,包括段落与节的使用、表格的自动化操作以及图片与形状的插入。最后,我们将通过一个实战示例——创建一个包含多种结构化元素的员工信息表,来综合运用所学知识。
使用段落(Paragraphs)与节(Sections)
段落和节是Word文档中重要的结构化元素。段落用于组织文本内容,而节则用于对文档进行分段,以便为不同部分设置不同的页面布局。
遍历文档中的所有段落
在处理Word文档时,经常需要遍历文档中的所有段落以进行批量操作。通过Paragraphs属性,我们可以轻松访问文档中的所有段落。- using MudTools.OfficeInterop;
- using MudTools.OfficeInterop.Word;
- // 打开现有文档
- using var wordApp = WordFactory.Open(@"C:\Documents\SampleDocument.docx");
- var document = wordApp.ActiveDocument;
- // 遍历文档中的所有段落
- foreach (var paragraph in document.Paragraphs)
- {
- // 输出段落文本
- Console.WriteLine(paragraph.GetText());
-
- // 为每个段落设置12磅的段后间距
- paragraph.SpaceAfter = 12;
-
- // 为每个段落设置1.5倍行距
- paragraph.LineSpacingRule = WdLineSpacing.wdLineSpace15;
- }
- // 或者通过索引访问特定段落
- for (int i = 1; i <= document.ParagraphCount; i++)
- {
- var paragraph = document.Paragraphs[i];
- // 处理段落内容
- Console.WriteLine($"第{i}段: {paragraph.GetText()}");
- }
复制代码 图片与形状的插入
图片和形状能够丰富文档的视觉效果,使其更加生动和易于理解。Word提供了两种类型的图形对象:内嵌形状和浮动形状。
使用InlineShapes.AddPicture方法插入图片
内嵌形状是嵌入在文本行中的对象,它们随着文本移动而移动。- /// <summary>
- /// 文档格式标准化工具
- /// </summary>
- public class DocumentFormatter
- {
- /// <summary>
- /// 标准化文档格式
- /// </summary>
- /// <param name="documentPath">文档路径</param>
- public void StandardizeDocument(string documentPath)
- {
- try
- {
- // 打开文档
- using var wordApp = WordFactory.Open(documentPath);
- var document = wordApp.ActiveDocument;
-
- // 隐藏Word应用程序以提高性能
- wordApp.Visibility = WordAppVisibility.Hidden;
- wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
-
- // 遍历所有段落并标准化格式
- foreach (var paragraph in document.Paragraphs)
- {
- // 设置段落格式
- paragraph.SpaceAfter = 12; // 段后间距12磅
- paragraph.SpaceBefore = 0; // 段前间距0磅
- paragraph.LineSpacingRule = WdLineSpacing.wdLineSpace15; // 1.5倍行距
-
- // 设置字体格式
- paragraph.Range.Font.Name = "微软雅黑";
- paragraph.Range.Font.Size = 10.5f;
-
- // 设置对齐方式
- paragraph.Alignment = WdParagraphAlignment.wdAlignParagraphJustify; // 两端对齐
- }
-
- // 保存文档
- document.Save();
- document.Close();
-
- Console.WriteLine($"文档 {documentPath} 格式标准化完成");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"格式标准化过程中发生错误: {ex.Message}");
- }
- }
- }
复制代码 使用Shapes.AddPicture方法插入浮动图片并设置环绕方式
浮动形状是独立于文本流的对象,可以放置在页面上的任意位置,并可以设置文字环绕方式。- // 添加新节并设置不同的页面方向
- var sections = document.Sections;
- // 获取当前节的数量
- int sectionCount = sections.Count;
- // 在文档末尾添加分节符以创建新节
- document.AddSectionBreak(document.Content.End - 1, (int)WdSectionBreakType.wdSectionBreakNextPage);
- // 获取新添加的节
- var newSection = sections[sectionCount + 1];
- // 为新节设置横向页面
- newSection.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
- // 为不同节设置不同的页眉
- var firstSectionHeader = sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
- firstSectionHeader.Range.Text = "这是第一节的页眉";
- var newSectionHeader = newSection.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
- newSectionHeader.Range.Text = "这是新节的页眉";
复制代码 应用场景:自动化制作产品宣传册
在市场营销领域,经常需要制作产品宣传册。通过自动化生成,可以快速制作大量标准化的宣传材料。- /// <summary>
- /// 混合布局报告生成器
- /// </summary>
- public class MixedLayoutReportGenerator
- {
- /// <summary>
- /// 生成混合布局报告
- /// </summary>
- /// <param name="templatePath">模板路径</param>
- /// <param name="outputPath">输出路径</param>
- public void GenerateReport(string templatePath, string outputPath)
- {
- try
- {
- // 基于模板创建文档
- using var wordApp = WordFactory.CreateFrom(templatePath);
- var document = wordApp.ActiveDocument;
-
- // 隐藏Word应用程序
- wordApp.Visibility = WordAppVisibility.Hidden;
- wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
-
- // 在文档末尾添加分节符,创建新节用于横向表格
- document.AddSectionBreak(document.Content.End - 1,
- (int)WdSectionBreakType.wdSectionBreakNextPage);
-
- // 获取新节
- var dataSection = document.Sections[document.Sections.Count];
-
- // 设置新节为横向布局
- dataSection.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
-
- // 在新节中添加标题
- var range = dataSection.Range;
- range.Collapse(WdCollapseDirection.wdCollapseStart);
- range.Text = "数据汇总表\n";
- range.Font.Bold = 1;
- range.Font.Size = 14;
- range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
-
- // 添加表格
- range.Collapse(WdCollapseDirection.wdCollapseEnd);
- var table = document.Tables.Add(range, 10, 6); // 10行6列的表格
-
- // 填充表格数据
- PopulateTableData(table);
-
- // 保存文档
- document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
- document.Close();
-
- Console.WriteLine($"混合布局报告已生成: {outputPath}");
- }
- catch (Exception ex)
- {
- Console.WriteLine($"生成报告时发生错误: {ex.Message}");
- }
- }
-
- /// <summary>
- /// 填充表格数据
- /// </summary>
- /// <param name="table">表格对象</param>
- private void PopulateTableData(IWordTable table)
- {
- // 表头
- string[] headers = { "序号", "产品名称", "销售数量", "单价", "总金额", "备注" };
- for (int i = 0; i < headers.Length; i++)
- {
- table.Cell(1, i + 1).Range.Text = headers[i];
- table.Cell(1, i + 1).Range.Font.Bold = 1;
- table.Cell(1, i + 1).VerticalAlignment =
- WdCellVerticalAlignment.wdCellAlignVerticalCenter;
- }
-
- // 示例数据
- string[,] data = {
- {"1", "产品A", "100", "50.00", "5000.00", ""},
- {"2", "产品B", "200", "30.00", "6000.00", ""},
- {"3", "产品C", "150", "40.00", "6000.00", ""},
- {"4", "产品D", "80", "70.00", "5600.00", ""},
- {"5", "产品E", "120", "35.00", "4200.00", ""}
- };
-
- // 填充数据
- for (int i = 0; i < data.GetLength(0); i++)
- {
- for (int j = 0; j < data.GetLength(1); j++)
- {
- table.Cell(i + 2, j + 1).Range.Text = data[i, j];
- table.Cell(i + 2, j + 1).VerticalAlignment =
- WdCellVerticalAlignment.wdCellAlignVerticalCenter;
- }
- }
-
- // 设置表格样式
- table.Borders.Enable = 1;
- table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
- table.PreferredWidth = 100;
- }
- }
复制代码 实战案例:创建员工信息表
现在,让我们通过一个完整的示例来综合运用所学知识,创建一个包含多种结构化元素的员工信息表。
[code]using MudTools.OfficeInterop;using MudTools.OfficeInterop.Word;using System;public class EmployeeInfoReportGenerator{ /// /// 生成员工信息报告 /// public void GenerateEmployeeReport() { try { // 创建新的Word文档 using var wordApp = WordFactory.BlankWorkbook(); var document = wordApp.ActiveDocument; wordApp.Visibility = WordAppVisibility.Hidden; wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; // 设置文档页面布局 document.PageSetup.Orientation = WdOrientation.wdOrientPortrait; document.PageSetup.TopMargin = 72; // 1英寸 = 72磅 document.PageSetup.BottomMargin = 72; document.PageSetup.LeftMargin = 72; document.PageSetup.RightMargin = 72; // 添加标题 var titleParagraph = document.AddParagraph(0, "员工信息报告"); titleParagraph.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; titleParagraph.Range.Font.Name = "微软雅黑"; titleParagraph.Range.Font.Size = 20; titleParagraph.Range.Font.Bold = 1; // 添加空行 document.AddParagraph(document.Content.End - 1); // 添加报告日期 var dateParagraph = document.AddParagraph(document.Content.End - 1, $"生成日期: {DateTime.Now:yyyy年MM月dd日}"); dateParagraph.Alignment = WdParagraphAlignment.wdAlignParagraphRight; dateParagraph.Range.Font.Size = 12; // 添加空行 document.AddParagraph(document.Content.End - 1); document.AddParagraph(document.Content.End - 1); // 创建员工信息表格 var tableRange = document.Content; tableRange.Collapse(WdCollapseDirection.wdCollapseEnd); var table = document.Tables.Add(tableRange, 6, 5); // 5行数据+1行标题 // 设置表格标题行 string[] headers = { "员工编号", "姓名", "部门", "职位", "入职日期" }; for (int i = 1; i |