找回密码
 立即注册
首页 业界区 安全 .NET驾驭Word之力:结构化文档元素操作

.NET驾驭Word之力:结构化文档元素操作

涅牵 2025-9-22 14:54:55
在前几篇文章中,我们学习了Word对象模型的基础知识、文本操作与格式设置等内容。掌握了这些基础知识后,我们现在可以进一步深入到文档的结构化元素操作,包括段落与节的管理、表格的创建与操作以及图片的插入等。
本文将详细介绍如何使用MudTools.OfficeInterop.Word库来操作Word文档中的结构化元素,包括段落与节的使用、表格的自动化操作以及图片与形状的插入。最后,我们将通过一个实战示例——创建一个包含多种结构化元素的员工信息表,来综合运用所学知识。
使用段落(Paragraphs)与节(Sections)

段落和节是Word文档中重要的结构化元素。段落用于组织文本内容,而节则用于对文档进行分段,以便为不同部分设置不同的页面布局。
遍历文档中的所有段落

在处理Word文档时,经常需要遍历文档中的所有段落以进行批量操作。通过Paragraphs属性,我们可以轻松访问文档中的所有段落。
  1. using MudTools.OfficeInterop;
  2. using MudTools.OfficeInterop.Word;
  3. // 打开现有文档
  4. using var wordApp = WordFactory.Open(@"C:\Documents\SampleDocument.docx");
  5. var document = wordApp.ActiveDocument;
  6. // 遍历文档中的所有段落
  7. foreach (var paragraph in document.Paragraphs)
  8. {
  9.     // 输出段落文本
  10.     Console.WriteLine(paragraph.GetText());
  11.    
  12.     // 为每个段落设置12磅的段后间距
  13.     paragraph.SpaceAfter = 12;
  14.    
  15.     // 为每个段落设置1.5倍行距
  16.     paragraph.LineSpacingRule = WdLineSpacing.wdLineSpace15;
  17. }
  18. // 或者通过索引访问特定段落
  19. for (int i = 1; i <= document.ParagraphCount; i++)
  20. {
  21.     var paragraph = document.Paragraphs[i];
  22.     // 处理段落内容
  23.     Console.WriteLine($"第{i}段: {paragraph.GetText()}");
  24. }
复制代码
图片与形状的插入

图片和形状能够丰富文档的视觉效果,使其更加生动和易于理解。Word提供了两种类型的图形对象:内嵌形状和浮动形状。
使用InlineShapes.AddPicture方法插入图片

内嵌形状是嵌入在文本行中的对象,它们随着文本移动而移动。
  1. /// <summary>
  2. /// 文档格式标准化工具
  3. /// </summary>
  4. public class DocumentFormatter
  5. {
  6.     /// <summary>
  7.     /// 标准化文档格式
  8.     /// </summary>
  9.     /// <param name="documentPath">文档路径</param>
  10.     public void StandardizeDocument(string documentPath)
  11.     {
  12.         try
  13.         {
  14.             // 打开文档
  15.             using var wordApp = WordFactory.Open(documentPath);
  16.             var document = wordApp.ActiveDocument;
  17.             
  18.             // 隐藏Word应用程序以提高性能
  19.             wordApp.Visibility = WordAppVisibility.Hidden;
  20.             wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
  21.             
  22.             // 遍历所有段落并标准化格式
  23.             foreach (var paragraph in document.Paragraphs)
  24.             {
  25.                 // 设置段落格式
  26.                 paragraph.SpaceAfter = 12;  // 段后间距12磅
  27.                 paragraph.SpaceBefore = 0;  // 段前间距0磅
  28.                 paragraph.LineSpacingRule = WdLineSpacing.wdLineSpace15; // 1.5倍行距
  29.                
  30.                 // 设置字体格式
  31.                 paragraph.Range.Font.Name = "微软雅黑";
  32.                 paragraph.Range.Font.Size = 10.5f;
  33.                
  34.                 // 设置对齐方式
  35.                 paragraph.Alignment = WdParagraphAlignment.wdAlignParagraphJustify; // 两端对齐
  36.             }
  37.             
  38.             // 保存文档
  39.             document.Save();
  40.             document.Close();
  41.             
  42.             Console.WriteLine($"文档 {documentPath} 格式标准化完成");
  43.         }
  44.         catch (Exception ex)
  45.         {
  46.             Console.WriteLine($"格式标准化过程中发生错误: {ex.Message}");
  47.         }
  48.     }
  49. }
复制代码
使用Shapes.AddPicture方法插入浮动图片并设置环绕方式

浮动形状是独立于文本流的对象,可以放置在页面上的任意位置,并可以设置文字环绕方式。
  1. // 添加新节并设置不同的页面方向
  2. var sections = document.Sections;
  3. // 获取当前节的数量
  4. int sectionCount = sections.Count;
  5. // 在文档末尾添加分节符以创建新节
  6. document.AddSectionBreak(document.Content.End - 1, (int)WdSectionBreakType.wdSectionBreakNextPage);
  7. // 获取新添加的节
  8. var newSection = sections[sectionCount + 1];
  9. // 为新节设置横向页面
  10. newSection.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
  11. // 为不同节设置不同的页眉
  12. var firstSectionHeader = sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
  13. firstSectionHeader.Range.Text = "这是第一节的页眉";
  14. var newSectionHeader = newSection.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
  15. newSectionHeader.Range.Text = "这是新节的页眉";
复制代码
应用场景:自动化制作产品宣传册

在市场营销领域,经常需要制作产品宣传册。通过自动化生成,可以快速制作大量标准化的宣传材料。
  1. /// <summary>
  2. /// 混合布局报告生成器
  3. /// </summary>
  4. public class MixedLayoutReportGenerator
  5. {
  6.     /// <summary>
  7.     /// 生成混合布局报告
  8.     /// </summary>
  9.     /// <param name="templatePath">模板路径</param>
  10.     /// <param name="outputPath">输出路径</param>
  11.     public void GenerateReport(string templatePath, string outputPath)
  12.     {
  13.         try
  14.         {
  15.             // 基于模板创建文档
  16.             using var wordApp = WordFactory.CreateFrom(templatePath);
  17.             var document = wordApp.ActiveDocument;
  18.             
  19.             // 隐藏Word应用程序
  20.             wordApp.Visibility = WordAppVisibility.Hidden;
  21.             wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
  22.             
  23.             // 在文档末尾添加分节符,创建新节用于横向表格
  24.             document.AddSectionBreak(document.Content.End - 1,
  25.                 (int)WdSectionBreakType.wdSectionBreakNextPage);
  26.             
  27.             // 获取新节
  28.             var dataSection = document.Sections[document.Sections.Count];
  29.             
  30.             // 设置新节为横向布局
  31.             dataSection.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
  32.             
  33.             // 在新节中添加标题
  34.             var range = dataSection.Range;
  35.             range.Collapse(WdCollapseDirection.wdCollapseStart);
  36.             range.Text = "数据汇总表\n";
  37.             range.Font.Bold = 1;
  38.             range.Font.Size = 14;
  39.             range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
  40.             
  41.             // 添加表格
  42.             range.Collapse(WdCollapseDirection.wdCollapseEnd);
  43.             var table = document.Tables.Add(range, 10, 6); // 10行6列的表格
  44.             
  45.             // 填充表格数据
  46.             PopulateTableData(table);
  47.             
  48.             // 保存文档
  49.             document.SaveAs(outputPath, WdSaveFormat.wdFormatXMLDocument);
  50.             document.Close();
  51.             
  52.             Console.WriteLine($"混合布局报告已生成: {outputPath}");
  53.         }
  54.         catch (Exception ex)
  55.         {
  56.             Console.WriteLine($"生成报告时发生错误: {ex.Message}");
  57.         }
  58.     }
  59.    
  60.     /// <summary>
  61.     /// 填充表格数据
  62.     /// </summary>
  63.     /// <param name="table">表格对象</param>
  64.     private void PopulateTableData(IWordTable table)
  65.     {
  66.         // 表头
  67.         string[] headers = { "序号", "产品名称", "销售数量", "单价", "总金额", "备注" };
  68.         for (int i = 0; i < headers.Length; i++)
  69.         {
  70.             table.Cell(1, i + 1).Range.Text = headers[i];
  71.             table.Cell(1, i + 1).Range.Font.Bold = 1;
  72.             table.Cell(1, i + 1).VerticalAlignment =
  73.                 WdCellVerticalAlignment.wdCellAlignVerticalCenter;
  74.         }
  75.         
  76.         // 示例数据
  77.         string[,] data = {
  78.             {"1", "产品A", "100", "50.00", "5000.00", ""},
  79.             {"2", "产品B", "200", "30.00", "6000.00", ""},
  80.             {"3", "产品C", "150", "40.00", "6000.00", ""},
  81.             {"4", "产品D", "80", "70.00", "5600.00", ""},
  82.             {"5", "产品E", "120", "35.00", "4200.00", ""}
  83.         };
  84.         
  85.         // 填充数据
  86.         for (int i = 0; i < data.GetLength(0); i++)
  87.         {
  88.             for (int j = 0; j < data.GetLength(1); j++)
  89.             {
  90.                 table.Cell(i + 2, j + 1).Range.Text = data[i, j];
  91.                 table.Cell(i + 2, j + 1).VerticalAlignment =
  92.                     WdCellVerticalAlignment.wdCellAlignVerticalCenter;
  93.             }
  94.         }
  95.         
  96.         // 设置表格样式
  97.         table.Borders.Enable = 1;
  98.         table.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
  99.         table.PreferredWidth = 100;
  100.     }
  101. }
复制代码
实战案例:创建员工信息表

现在,让我们通过一个完整的示例来综合运用所学知识,创建一个包含多种结构化元素的员工信息表。
[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

相关推荐

您需要登录后才可以回帖 登录 | 立即注册