Aspose.Words for .NET 教程(十三):样式系统完全指南

作者:微信公众号:【架构师老卢】
9-22 19:50
25

Aspose.Words for .NET下载地址 https://soft51.cc/software/175811283999782847

样式系统是 Microsoft Word 文档格式化的核心机制,它允许我们定义一组格式设置并将其应用到文档的不同部分。Aspose.Words for .NET 提供了完整的样式管理功能,包括内置样式的使用、自定义样式的创建、样式层次管理等。掌握样式系统可以大大提高文档格式化的效率和一致性。

13.1 内置样式的应用与修改

Word 文档包含了大量预定义的内置样式,如标题样式、正文样式、引用样式等。这些样式可以直接应用,也可以根据需要进行修改。

13.1.1 应用内置样式

using Aspose.Words;
using Aspose.Words.Drawing;
using System;

class Program
{
    static void Main()
    {
        // 创建文档和构建器
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 应用标题1样式
        builder.ParagraphFormat.StyleName = "Heading 1";
        builder.Writeln("第一章 样式系统概述");

        // 应用标题2样式
        builder.ParagraphFormat.StyleName = "Heading 2";
        builder.Writeln("1.1 什么是样式");

        // 应用正文样式
        builder.ParagraphFormat.StyleName = "Normal";
        builder.Writeln("样式是一组预定义的格式设置,包括字体、段落格式、边框等属性。");

        // 应用引用样式
        builder.ParagraphFormat.StyleName = "Quote";
        builder.Writeln("这是一个引用段落,通常用于显示重要的引文内容。");

        // 应用强调样式
        builder.ParagraphFormat.StyleName = "Intense Quote";
        builder.Writeln("这是一个强调引用段落。");

        // 保存文档
        doc.Save("内置样式应用示例.docx");
        Console.WriteLine("内置样式应用完成!");
    }
}

13.1.2 修改内置样式

using Aspose.Words;
using Aspose.Words.Drawing;
using System.Drawing;

class Program
{
    static void Main()
    {
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 获取并修改标题1样式
        Style heading1Style = doc.Styles[StyleIdentifier.Heading1];
        
        // 修改字体属性
        heading1Style.Font.Name = "微软雅黑";
        heading1Style.Font.Size = 18;
        heading1Style.Font.Bold = true;
        heading1Style.Font.Color = Color.DarkBlue;
        
        // 修改段落属性
        heading1Style.ParagraphFormat.SpaceAfter = 12;
        heading1Style.ParagraphFormat.SpaceBefore = 12;
        heading1Style.ParagraphFormat.KeepWithNext = true;
        
        // 应用修改后的样式
        builder.ParagraphFormat.StyleName = "Heading 1";
        builder.Writeln("修改后的标题1样式");

        // 修改正文样式
        Style normalStyle = doc.Styles[StyleIdentifier.Normal];
        normalStyle.Font.Name = "宋体";
        normalStyle.Font.Size = 12;
        normalStyle.ParagraphFormat.LineSpacing = 18; // 1.5倍行距
        normalStyle.ParagraphFormat.FirstLineIndent = 24; // 首行缩进2字符

        builder.ParagraphFormat.StyleName = "Normal";
        builder.Writeln("这是修改后的正文样式,字体为宋体,12号字,1.5倍行距,首行缩进2字符。");

        doc.Save("修改内置样式示例.docx");
        Console.WriteLine("内置样式修改完成!");
    }
}

13.2 自定义样式创建

除了使用内置样式,我们还可以创建自定义样式来满足特定的格式需求。

13.2.1 创建自定义段落样式

using Aspose.Words;
using Aspose.Words.Drawing;
using System.Drawing;

class Program
{
    static void Main()
    {
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 创建自定义段落样式
        Style customParagraphStyle = doc.Styles.Add(StyleType.Paragraph, "自定义段落样式");
        
        // 设置字体属性
        customParagraphStyle.Font.Name = "微软雅黑";
        customParagraphStyle.Font.Size = 14;
        customParagraphStyle.Font.Color = Color.DarkGreen;
        customParagraphStyle.Font.Bold = true;
        
        // 设置段落属性
        customParagraphStyle.ParagraphFormat.Alignment = ParagraphAlignment.Center;
        customParagraphStyle.ParagraphFormat.SpaceAfter = 15;
        customParagraphStyle.ParagraphFormat.SpaceBefore = 10;
        
        // 设置边框
        customParagraphStyle.ParagraphFormat.Borders.Bottom.LineStyle = LineStyle.Single;
        customParagraphStyle.ParagraphFormat.Borders.Bottom.LineWidth = 2;
        customParagraphStyle.ParagraphFormat.Borders.Bottom.Color = Color.DarkGreen;
        
        // 应用自定义样式
        builder.ParagraphFormat.StyleName = "自定义段落样式";
        builder.Writeln("这是使用自定义段落样式的文本");

        // 创建另一个自定义样式 - 注意框样式
        Style noteBoxStyle = doc.Styles.Add(StyleType.Paragraph, "注意框");
        noteBoxStyle.Font.Name = "宋体";
        noteBoxStyle.Font.Size = 12;
        noteBoxStyle.Font.Color = Color.DarkRed;
        
        // 设置背景色和边框
        noteBoxStyle.ParagraphFormat.Shading.BackgroundPatternColor = Color.LightYellow;
        noteBoxStyle.ParagraphFormat.Borders.LineStyle = LineStyle.Single;
        noteBoxStyle.ParagraphFormat.Borders.Color = Color.Red;
        noteBoxStyle.ParagraphFormat.LeftIndent = 20;
        noteBoxStyle.ParagraphFormat.RightIndent = 20;
        noteBoxStyle.ParagraphFormat.SpaceAfter = 10;
        noteBoxStyle.ParagraphFormat.SpaceBefore = 10;

        builder.ParagraphFormat.StyleName = "注意框";
        builder.Writeln("注意:这是一个重要提示框,用于显示需要特别注意的内容。");

        doc.Save("自定义段落样式示例.docx");
        Console.WriteLine("自定义段落样式创建完成!");
    }
}

13.2.2 创建自定义字符样式

using Aspose.Words;
using Aspose.Words.Drawing;
using System.Drawing;

class Program
{
    static void Main()
    {
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 创建自定义字符样式 - 高亮文本
        Style highlightStyle = doc.Styles.Add(StyleType.Character, "高亮文本");
        highlightStyle.Font.Color = Color.White;
        highlightStyle.Font.Shading.BackgroundPatternColor = Color.Orange;
        highlightStyle.Font.Bold = true;

        // 创建自定义字符样式 - 代码文本
        Style codeStyle = doc.Styles.Add(StyleType.Character, "代码文本");
        codeStyle.Font.Name = "Courier New";
        codeStyle.Font.Size = 10;
        codeStyle.Font.Color = Color.DarkBlue;
        codeStyle.Font.Shading.BackgroundPatternColor = Color.LightGray;

        // 创建自定义字符样式 - 链接文本
        Style linkStyle = doc.Styles.Add(StyleType.Character, "链接文本");
        linkStyle.Font.Color = Color.Blue;
        linkStyle.Font.Underline = Underline.Single;

        // 使用字符样式
        builder.Write("这是普通文本,");
        builder.Font.StyleName = "高亮文本";
        builder.Write("这是高亮文本");
        builder.Font.StyleName = "Normal";
        builder.Write(",这里有一段");
        builder.Font.StyleName = "代码文本";
        builder.Write("Console.WriteLine(\"Hello World\");");
        builder.Font.StyleName = "Normal";
        builder.Write("代码,还有一个");
        builder.Font.StyleName = "链接文本";
        builder.Write("www.example.com");
        builder.Font.StyleName = "Normal";
        builder.Write("链接。");

        doc.Save("自定义字符样式示例.docx");
        Console.WriteLine("自定义字符样式创建完成!");
    }
}

13.3 字符样式与段落样式

理解字符样式和段落样式的区别对于有效使用样式系统非常重要。

13.3.1 样式类型对比

using Aspose.Words;
using Aspose.Words.Drawing;
using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 演示段落样式和字符样式的区别
        
        // 1. 段落样式示例
        Style paragraphStyle = doc.Styles.Add(StyleType.Paragraph, "示例段落样式");
        paragraphStyle.Font.Name = "微软雅黑";
        paragraphStyle.Font.Size = 14;
        paragraphStyle.Font.Color = Color.DarkBlue;
        paragraphStyle.ParagraphFormat.Alignment = ParagraphAlignment.Justify;
        paragraphStyle.ParagraphFormat.FirstLineIndent = 24;
        paragraphStyle.ParagraphFormat.LineSpacing = 20;

        builder.ParagraphFormat.StyleName = "示例段落样式";
        builder.Writeln("这是段落样式的示例。段落样式会影响整个段落的格式,包括字体、对齐方式、缩进、行距等。");

        // 2. 字符样式示例
        Style characterStyle = doc.Styles.Add(StyleType.Character, "示例字符样式");
        characterStyle.Font.Name = "Courier New";
        characterStyle.Font.Size = 12;
        characterStyle.Font.Color = Color.Red;
        characterStyle.Font.Bold = true;

        builder.ParagraphFormat.StyleName = "Normal";
        builder.Write("这是普通段落中的文本,");
        builder.Font.StyleName = "示例字符样式";
        builder.Write("这部分文本应用了字符样式");
        builder.Font.StyleName = "Normal";
        builder.Write(",这部分又回到了普通格式。");

        // 3. 混合使用示例
        builder.InsertParagraph();
        builder.ParagraphFormat.StyleName = "示例段落样式";
        builder.Write("这个段落应用了段落样式,");
        builder.Font.StyleName = "示例字符样式";
        builder.Write("同时这部分文本还应用了字符样式");
        builder.Font.StyleName = "Normal";
        builder.Write(",展示了样式的叠加效果。");

        doc.Save("样式类型对比示例.docx");
        Console.WriteLine("样式类型对比示例创建完成!");
    }
}

13.4 样式层次与继承关系

样式系统支持继承机制,子样式可以继承父样式的属性,并在此基础上进行修改。

13.4.1 样式继承示例

using Aspose.Words;
using Aspose.Words.Drawing;
using System.Drawing;

class Program
{
    static void Main()
    {
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 创建基础样式(父样式)
        Style baseStyle = doc.Styles.Add(StyleType.Paragraph, "基础样式");
        baseStyle.Font.Name = "微软雅黑";
        baseStyle.Font.Size = 12;
        baseStyle.Font.Color = Color.Black;
        baseStyle.ParagraphFormat.SpaceAfter = 10;
        baseStyle.ParagraphFormat.LineSpacing = 18;

        // 创建继承样式1(子样式)
        Style childStyle1 = doc.Styles.Add(StyleType.Paragraph, "子样式1");
        childStyle1.BaseStyleName = "基础样式"; // 设置继承关系
        childStyle1.Font.Bold = true; // 只修改粗体属性
        childStyle1.Font.Color = Color.DarkBlue; // 修改颜色

        // 创建继承样式2(子样式)
        Style childStyle2 = doc.Styles.Add(StyleType.Paragraph, "子样式2");
        childStyle2.BaseStyleName = "基础样式"; // 设置继承关系
        childStyle2.Font.Italic = true; // 只修改斜体属性
        childStyle2.Font.Color = Color.DarkGreen; // 修改颜色
        childStyle2.ParagraphFormat.Alignment = ParagraphAlignment.Center; // 修改对齐方式

        // 创建孙样式
        Style grandChildStyle = doc.Styles.Add(StyleType.Paragraph, "孙样式");
        grandChildStyle.BaseStyleName = "子样式1"; // 继承自子样式1
        grandChildStyle.Font.Underline = Underline.Single; // 添加下划线

        // 应用不同层次的样式
        builder.ParagraphFormat.StyleName = "基础样式";
        builder.Writeln("这是基础样式的文本,微软雅黑,12号字,黑色。");

        builder.ParagraphFormat.StyleName = "子样式1";
        builder.Writeln("这是子样式1的文本,继承了基础样式,但是粗体和深蓝色。");

        builder.ParagraphFormat.StyleName = "子样式2";
        builder.Writeln("这是子样式2的文本,继承了基础样式,但是斜体、深绿色并居中对齐。");

        builder.ParagraphFormat.StyleName = "孙样式";
        builder.Writeln("这是孙样式的文本,继承了子样式1,同时添加了下划线。");

        // 演示继承关系查看
        Console.WriteLine("样式继承关系:");
        foreach (Style style in doc.Styles)
        {
            if (style.Type == StyleType.Paragraph && !string.IsNullOrEmpty(style.BaseStyleName))
            {
                Console.WriteLine($"{style.Name} 继承自 {style.BaseStyleName}");
            }
        }

        doc.Save("样式继承示例.docx");
        Console.WriteLine("样式继承示例创建完成!");
    }
}

13.5 样式集管理

样式集是一组相关样式的集合,可以作为一个整体进行管理和应用。

13.5.1 样式集操作

using Aspose.Words;
using Aspose.Words.Drawing;
using System;
using System.Drawing;
using System.Linq;

class Program
{
    static void Main()
    {
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // 创建一套完整的样式集
        CreateDocumentStyleSet(doc);
        
        // 使用样式集创建文档
        CreateDocumentWithStyleSet(builder);
        
        // 列出所有自定义样式
        ListCustomStyles(doc);
        
        // 应用样式集
        ApplyStyleSet(builder);

        doc.Save("样式集管理示例.docx");
        Console.WriteLine("样式集管理示例创建完成!");
    }

    static void CreateDocumentStyleSet(Document doc)
    {
        // 创建文档标题样式集
        Style titleStyle = doc.Styles.Add(StyleType.Paragraph, "文档标题");
        titleStyle.Font.Name = "黑体";
        titleStyle.Font.Size = 22;
        titleStyle.Font.Bold = true;
        titleStyle.Font.Color = Color.DarkBlue;
        titleStyle.ParagraphFormat.Alignment = ParagraphAlignment.Center;
        titleStyle.ParagraphFormat.SpaceAfter = 20;

        Style subTitleStyle = doc.Styles.Add(StyleType.Paragraph, "文档副标题");
        subTitleStyle.BaseStyleName = "文档标题";
        subTitleStyle.Font.Size = 16;
        subTitleStyle.Font.Color = Color.DarkGray;
        subTitleStyle.ParagraphFormat.SpaceAfter = 15;

        // 创建章节标题样式集
        Style chapterStyle = doc.Styles.Add(StyleType.Paragraph, "章节标题");
        chapterStyle.Font.Name = "微软雅黑";
        chapterStyle.Font.Size = 18;
        chapterStyle.Font.Bold = true;
        chapterStyle.Font.Color = Color.DarkRed;
        chapterStyle.ParagraphFormat.SpaceBefore = 15;
        chapterStyle.ParagraphFormat.SpaceAfter = 10;
        chapterStyle.ParagraphFormat.KeepWithNext = true;

        Style sectionStyle = doc.Styles.Add(StyleType.Paragraph, "节标题");
        sectionStyle.BaseStyleName = "章节标题";
        sectionStyle.Font.Size = 14;
        sectionStyle.Font.Color = Color.DarkGreen;

        // 创建正文样式集
        Style bodyStyle = doc.Styles.Add(StyleType.Paragraph, "正文");
        bodyStyle.Font.Name = "宋体";
        bodyStyle.Font.Size = 12;
        bodyStyle.ParagraphFormat.FirstLineIndent = 24;
        bodyStyle.ParagraphFormat.LineSpacing = 18;
        bodyStyle.ParagraphFormat.SpaceAfter = 6;

        Style quotationStyle = doc.Styles.Add(StyleType.Paragraph, "引用");
        quotationStyle.BaseStyleName = "正文";
        quotationStyle.Font.Italic = true;
        quotationStyle.Font.Color = Color.DarkGray;
        quotationStyle.ParagraphFormat.LeftIndent = 40;
        quotationStyle.ParagraphFormat.RightIndent = 40;

        // 创建强调样式集(字符样式)
        Style emphasisStyle = doc.Styles.Add(StyleType.Character, "强调");
        emphasisStyle.Font.Bold = true;
        emphasisStyle.Font.Color = Color.Red;

        Style keywordStyle = doc.Styles.Add(StyleType.Character, "关键词");
        keywordStyle.Font.Bold = true;
        keywordStyle.Font.Color = Color.Blue;
        keywordStyle.Font.Shading.BackgroundPatternColor = Color.LightYellow;
    }

    static void CreateDocumentWithStyleSet(DocumentBuilder builder)
    {
        // 使用样式集创建完整文档
        builder.ParagraphFormat.StyleName = "文档标题";
        builder.Writeln("Aspose.Words 样式系统");

        builder.ParagraphFormat.StyleName = "文档副标题";
        builder.Writeln("样式集管理与应用实践");

        builder.ParagraphFormat.StyleName = "章节标题";
        builder.Writeln("第一章 样式系统概述");

        builder.ParagraphFormat.StyleName = "节标题";
        builder.Writeln("1.1 什么是样式");

        builder.ParagraphFormat.StyleName = "正文";
        builder.Write("样式是文档格式化的");
        builder.Font.StyleName = "强调";
        builder.Write("核心机制");
        builder.Font.StyleName = "Normal";
        builder.Write(",它定义了文本和段落的外观。通过使用");
        builder.Font.StyleName = "关键词";
        builder.Write("样式集");
        builder.Font.StyleName = "Normal";
        builder.Write(",我们可以确保文档格式的一致性和专业性。");

        builder.ParagraphFormat.StyleName = "引用";
        builder.Writeln("\"好的文档设计需要统一的样式规范,这不仅提高了可读性,也体现了专业性。\"");

        builder.ParagraphFormat.StyleName = "节标题";
        builder.Writeln("1.2 样式的优势");

        builder.ParagraphFormat.StyleName = "正文";
        builder.Writeln("使用样式系统具有以下优势:提高效率、保持一致性、便于维护、支持批量修改等。");
    }

    static void ListCustomStyles(Document doc)
    {
        Console.WriteLine("\n自定义样式列表:");
        Console.WriteLine("段落样式:");
        foreach (Style style in doc.Styles.Where(s => s.Type == StyleType.Paragraph && !s.BuiltIn))
        {
            Console.WriteLine($"  - {style.Name}");
            if (!string.IsNullOrEmpty(style.BaseStyleName))
            {
                Console.WriteLine($"    继承自: {style.BaseStyleName}");
            }
        }

        Console.WriteLine("字符样式:");
        foreach (Style style in doc.Styles.Where(s => s.Type == StyleType.Character && !s.BuiltIn))
        {
            Console.WriteLine($"  - {style.Name}");
        }
    }

    static void ApplyStyleSet(DocumentBuilder builder)
    {
        builder.InsertBreak(BreakType.PageBreak);
        
        // 演示样式集的统一应用
        builder.ParagraphFormat.StyleName = "文档标题";
        builder.Writeln("样式集应用演示");

        builder.ParagraphFormat.StyleName = "章节标题";
        builder.Writeln("技术文档示例");

        builder.ParagraphFormat.StyleName = "正文";
        builder.Write("本文档演示了如何使用");
        builder.Font.StyleName = "关键词";
        builder.Write("Aspose.Words");
        builder.Font.StyleName = "Normal";
        builder.Write("进行");
        builder.Font.StyleName = "强调";
        builder.Write("专业文档");
        builder.Font.StyleName = "Normal";
        builder.Write("的样式管理。");
    }
}

13.6 样式的导入导出

样式可以在不同文档之间进行导入和导出,实现样式的重用和标准化。

13.6.1 样式导入导出操作

using Aspose.Words;
using Aspose.Words.Drawing;
using System;
using System.Drawing;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        // 1. 创建样式模板文档
        CreateStyleTemplate();

        // 2. 创建目标文档并导入样式
        ImportStylesExample();

        // 3. 导出样式到新文档
        ExportStylesExample();

        // 4. 样式冲突处理
        HandleStyleConflicts();

        Console.WriteLine("样式导入导出操作完成!");
    }

    static void CreateStyleTemplate()
    {
        Document templateDoc = new Document();
        
        // 创建企业标准样式模板
        Style companyTitleStyle = templateDoc.Styles.Add(StyleType.Paragraph, "企业标题");
        companyTitleStyle.Font.Name = "微软雅黑";
        companyTitleStyle.Font.Size = 20;
        companyTitleStyle.Font.Bold = true;
        companyTitleStyle.Font.Color = Color.FromArgb(0, 70, 130); // 企业蓝
        companyTitleStyle.ParagraphFormat.Alignment = ParagraphAlignment.Center;
        companyTitleStyle.ParagraphFormat.SpaceAfter = 15;

        Style companyHeadingStyle = templateDoc.Styles.Add(StyleType.Paragraph, "企业标题2");
        companyHeadingStyle.BaseStyleName = "企业标题";
        companyHeadingStyle.Font.Size = 16;
        companyHeadingStyle.ParagraphFormat.Alignment = ParagraphAlignment.Left;

        Style companyBodyStyle = templateDoc.Styles.Add(StyleType.Paragraph, "企业正文");
        companyBodyStyle.Font.Name = "宋体";
        companyBodyStyle.Font.Size = 12;
        companyBodyStyle.ParagraphFormat.FirstLineIndent = 24;
        companyBodyStyle.ParagraphFormat.LineSpacing = 20;

        Style companyHighlightStyle = templateDoc.Styles.Add(StyleType.Character, "企业高亮");
        companyHighlightStyle.Font.Color = Color.FromArgb(0, 70, 130);
        companyHighlightStyle.Font.Bold = true;

        // 在模板中添加样式说明
        DocumentBuilder builder = new DocumentBuilder(templateDoc);
        builder.ParagraphFormat.StyleName = "企业标题";
        builder.Writeln("企业样式模板");

        builder.ParagraphFormat.StyleName = "企业标题2";
        builder.Writeln("样式说明");

        builder.ParagraphFormat.StyleName = "企业正文";
        builder.Write("这是企业标准样式模板,包含了");
        builder.Font.StyleName = "企业高亮";
        builder.Write("标准化的样式定义");
        builder.Font.StyleName = "Normal";
        builder.Write(",可以导入到其他文档中使用。");

        templateDoc.Save("企业样式模板.docx");
        Console.WriteLine("样式模板创建完成!");
    }

    static void ImportStylesExample()
    {
        // 创建新文档
        Document newDoc = new Document();
        DocumentBuilder builder = new DocumentBuilder(newDoc);

        // 从模板文档导入样式
        Document templateDoc = new Document("企业样式模板.docx");
        
        // 导入所有自定义样式
        foreach (Style style in templateDoc.Styles)
        {
            if (!style.BuiltIn)
            {
                // 检查样式是否已存在
                if (newDoc.Styles[style.Name] == null)
                {
                    // 导入样式
                    Style importedStyle = newDoc.Styles.Add(style.Type, style.Name);
                    importedStyle.CopyFrom(style);
                    Console.WriteLine($"导入样式: {style.Name}");
                }
            }
        }

        // 使用导入的样式创建内容
        builder.ParagraphFormat.StyleName = "企业标题";
        builder.Writeln("使用导入样式的文档");

        builder.ParagraphFormat.StyleName = "企业标题2";
        builder.Writeln("导入样式演示");

        builder.ParagraphFormat.StyleName = "企业正文";
        builder.Write("这个文档使用了从模板");
        builder.Font.StyleName = "企业高亮";
        builder.Write("导入的样式");
        builder.Font.StyleName = "Normal";
        builder.Write(",保持了格式的一致性。");

        newDoc.Save("导入样式示例.docx");
        Console.WriteLine("样式导入示例完成!");
    }

    static void ExportStylesExample()
    {
        // 创建包含自定义样式的源文档
        Document sourceDoc = new Document();
        
        // 创建一些样式
        Style exportStyle1 = sourceDoc.Styles.Add(StyleType.Paragraph, "导出样式1");
        exportStyle1.Font.Name = "Arial";
        exportStyle1.Font.Size = 14;
        exportStyle1.Font.Color = Color.Purple;

        Style exportStyle2 = sourceDoc.Styles.Add(StyleType.Character, "导出样式2");
        exportStyle2.Font.Bold = true;
        exportStyle2.Font.Color = Color.Orange;

        // 创建只包含样式的模板文档
        Document styleOnlyDoc = new Document();
        
        // 导出指定样式
        string[] stylesToExport = { "导出样式1", "导出样式2" };
        
        foreach (string styleName in stylesToExport)
        {
            Style sourceStyle = sourceDoc.Styles[styleName];
            if (sourceStyle != null)
            {
                Style exportedStyle = styleOnlyDoc.Styles.Add(sourceStyle.Type, sourceStyle.Name);
                exportedStyle.CopyFrom(sourceStyle);
                Console.WriteLine($"导出样式: {styleName}");
            }
        }

        // 添加样式示例内容
        DocumentBuilder builder = new DocumentBuilder(styleOnlyDoc);
        builder.ParagraphFormat.StyleName = "导出样式1";
        builder.Write("这是导出的段落样式示例,");
        builder.Font.StyleName = "导出样式2";
        builder.Write("这是导出的字符样式");
        builder.Font.StyleName = "Normal";
        builder.Write("示例。");

        styleOnlyDoc.Save("导出样式模板.docx");
        Console.WriteLine("样式导出示例完成!");
    }

    static void HandleStyleConflicts()
    {
        // 创建两个具有冲突样式名称的文档
        Document doc1 = new Document();
        Style style1 = doc1.Styles.Add(StyleType.Paragraph, "冲突样式");
        style1.Font.Color = Color.Red;
        style1.Font.Size = 14;

        Document doc2 = new Document();
        Style style2 = doc2.Styles.Add(StyleType.Paragraph, "冲突样式");
        style2.Font.Color = Color.Blue;
        style2.Font.Size = 16;

        // 处理样式冲突的几种策略

        // 策略1:跳过已存在的样式
        Console.WriteLine("\n策略1:跳过冲突样式");
        Document targetDoc1 = new Document();
        ImportStylesWithSkip(doc1, targetDoc1);
        ImportStylesWithSkip(doc2, targetDoc1);
        targetDoc1.Save("跳过冲突样式.docx");

        // 策略2:重命名冲突样式
        Console.WriteLine("\n策略2:重命名冲突样式");
        Document targetDoc2 = new Document();
        ImportStylesWithRename(doc1, targetDoc2, "");
        ImportStylesWithRename(doc2, targetDoc2, "_v2");
        targetDoc2.Save("重命名冲突样式.docx");

        // 策略3:覆盖已存在的样式
        Console.WriteLine("\n策略3:覆盖冲突样式");
        Document targetDoc3 = new Document();
        ImportStylesWithOverwrite(doc1, targetDoc3);
        ImportStylesWithOverwrite(doc2, targetDoc3);
        targetDoc3.Save("覆盖冲突样式.docx");
    }

    static void ImportStylesWithSkip(Document sourceDoc, Document targetDoc)
    {
        foreach (Style style in sourceDoc.Styles)
        {
            if (!style.BuiltIn && targetDoc.Styles[style.Name] == null)
            {
                Style newStyle = targetDoc.Styles.Add(style.Type, style.Name);
                newStyle.CopyFrom(style);
                Console.WriteLine($"导入样式: {style.Name}");
            }
            else if (!style.BuiltIn)
            {
                Console.WriteLine($"跳过冲突样式: {style.Name}");
            }
        }
    }

    static void ImportStylesWithRename(Document sourceDoc, Document targetDoc, string suffix)
    {
        foreach (Style style in sourceDoc.Styles)
        {
            if (!style.BuiltIn)
            {
                string newName = style.Name + suffix;
                if (targetDoc.Styles[newName] == null)
                {
                    Style newStyle = targetDoc.Styles.Add(style.Type, newName);
                    newStyle.CopyFrom(style);
                    Console.WriteLine($"导入样式: {style.Name} -> {newName}");
                }
            }
        }
    }

    static void ImportStylesWithOverwrite(Document sourceDoc, Document targetDoc)
    {
        foreach (Style style in sourceDoc.Styles)
        {
            if (!style.BuiltIn)
            {
                Style existingStyle = targetDoc.Styles[style.Name];
                if (existingStyle != null)
                {
                    existingStyle.CopyFrom(style);
                    Console.WriteLine($"覆盖样式: {style.Name}");
                }
                else
                {
                    Style newStyle = targetDoc.Styles.Add(style.Type, style.Name);
                    newStyle.CopyFrom(style);
                    Console.WriteLine($"导入样式: {style.Name}");
                }
            }
        }
    }
}

实用工具类

为了更好地管理样式,我们可以创建一个实用工具类:

using Aspose.Words;
using System;
using System.Collections.Generic;
using System.Linq;

public static class StyleManager
{
    /// <summary>
    /// 获取文档中所有自定义样式
    /// </summary>
    public static List<Style> GetCustomStyles(Document document)
    {
        return document.Styles.Where(s => !s.BuiltIn).ToList();
    }

    /// <summary>
    /// 获取指定类型的样式
    /// </summary>
    public static List<Style> GetStylesByType(Document document, StyleType styleType)
    {
        return document.Styles.Where(s => s.Type == styleType).ToList();
    }

    /// <summary>
    /// 检查样式是否存在
    /// </summary>
    public static bool StyleExists(Document document, string styleName)
    {
        return document.Styles[styleName] != null;
    }

    /// <summary>
    /// 安全删除样式
    /// </summary>
    public static bool DeleteStyle(Document document, string styleName)
    {
        try
        {
            Style style = document.Styles[styleName];
            if (style != null && !style.BuiltIn)
            {
                // 检查是否有其他样式继承此样式
                var inheritedStyles = document.Styles
                    .Where(s => s.BaseStyleName == styleName)
                    .ToList();

                if (inheritedStyles.Any())
                {
                    Console.WriteLine($"警告:样式 '{styleName}' 被以下样式继承:");
                    foreach (var inheritedStyle in inheritedStyles)
                    {
                        Console.WriteLine($"  - {inheritedStyle.Name}");
                    }
                    return false;
                }

                document.Styles.Remove(style);
                return true;
            }
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"删除样式时出错:{ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// 批量导入样式
    /// </summary>
    public static int ImportStyles(Document sourceDoc, Document targetDoc, 
        ImportStylesOptions options = ImportStylesOptions.SkipDuplicates)
    {
        int importedCount = 0;
        
        foreach (Style style in sourceDoc.Styles)
        {
            if (!style.BuiltIn)
            {
                switch (options)
                {
                    case ImportStylesOptions.SkipDuplicates:
                        if (targetDoc.Styles[style.Name] == null)
                        {
                            CreateStyleCopy(targetDoc, style);
                            importedCount++;
                        }
                        break;

                    case ImportStylesOptions.OverwriteExisting:
                        CreateStyleCopy(targetDoc, style);
                        importedCount++;
                        break;

                    case ImportStylesOptions.RenameConflicts:
                        string newName = GetUniqueStyleName(targetDoc, style.Name);
                        CreateStyleCopy(targetDoc, style, newName);
                        importedCount++;
                        break;
                }
            }
        }

        return importedCount;
    }

    private static void CreateStyleCopy(Document targetDoc, Style sourceStyle, string newName = null)
    {
        string styleName = newName ?? sourceStyle.Name;
        Style existingStyle = targetDoc.Styles[styleName];

        if (existingStyle != null)
        {
            existingStyle.CopyFrom(sourceStyle);
        }
        else
        {
            Style newStyle = targetDoc.Styles.Add(sourceStyle.Type, styleName);
            newStyle.CopyFrom(sourceStyle);
        }
    }

    private static string GetUniqueStyleName(Document document, string baseName)
    {
        if (document.Styles[baseName] == null)
            return baseName;

        int counter = 1;
        string newName;
        do
        {
            newName = $"{baseName}_{counter}";
            counter++;
        } while (document.Styles[newName] != null);

        return newName;
    }

    /// <summary>
    /// 显示样式信息
    /// </summary>
    public static void DisplayStyleInfo(Style style)
    {
        Console.WriteLine($"样式名称: {style.Name}");
        Console.WriteLine($"样式类型: {style.Type}");
        Console.WriteLine($"是否为内置样式: {style.BuiltIn}");
        
        if (!string.IsNullOrEmpty(style.BaseStyleName))
        {
            Console.WriteLine($"基础样式: {style.BaseStyleName}");
        }

        if (style.Type == StyleType.Paragraph)
        {
            Console.WriteLine($"字体: {style.Font.Name}, 大小: {style.Font.Size}");
            Console.WriteLine($"段落对齐: {style.ParagraphFormat.Alignment}");
        }
        else if (style.Type == StyleType.Character)
        {
            Console.WriteLine($"字体: {style.Font.Name}, 大小: {style.Font.Size}");
            Console.WriteLine($"粗体: {style.Font.Bold}, 斜体: {style.Font.Italic}");
        }

        Console.WriteLine("---");
    }
}

public enum ImportStylesOptions
{
    SkipDuplicates,
    OverwriteExisting,
    RenameConflicts
}

总结

本教程全面介绍了 Aspose.Words for .NET 中的样式系统,包括:

  1. 内置样式的应用与修改:学会如何使用和自定义 Word 的内置样式
  2. 自定义样式创建:掌握创建段落样式和字符样式的方法
  3. 样式类型理解:区分段落样式和字符样式的应用场景
  4. 样式继承机制:利用样式继承提高样式管理效率
  5. 样式集管理:创建和管理完整的样式体系
  6. 样式导入导出:实现样式在不同文档间的重用

样式系统是专业文档制作的基础,合理使用样式不仅能提高文档制作效率,还能确保文档格式的一致性和专业性。在实际项目中,建议创建标准的样式模板,并通过样式导入功能在团队中推广使用。

Aspose.Words for .NET下载地址 https://soft51.cc/software/175811283999782847

相关留言评论
昵称:
邮箱:
阅读排行