如何使用 C# 为 DOCX 中的文本添加样式;

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWord 的 TextStyle 类使 .NET 开发人员能够以编程方式将专业文本格式应用于 Word 文档,包括字体、颜色、粗体、斜体、下划线等。 无论是生成报告、创建模板还是自动创建文档,IronWord 都能提供全面的样式工具,复制 Microsoft Word 的格式选项。

as-heading:2(快速入门:使用 C# 在 DOCX 中为文本添加样式)

1.通过 NuGet 安装 IronWord:安装-打包 IronWord 2.创建 WordDocument 对象 3.用您的文本创建 TextContent 4.使用所需属性(字体、颜色、粗体等)应用 TextStyle 5.在段落中添加文本并保存文档

Nuget Icon立即开始使用 NuGet 创建 PDF 文件:

  1. 使用 NuGet 包管理器安装 IronWord

    PM > Install-Package IronWord

  2. 复制并运行这段代码。

    // Quick example
    using IronWord;
    using IronWord.Models;
    
    // Initialize a new Word document
    WordDocument doc = new WordDocument();
    
    // Create styled text content
    TextContent text = new TextContent("Styled text");
    
    // Apply styling properties
    text.Style = new TextStyle() 
    { 
        IsBold = true, 
        Color = Color.Red,
        TextFont = new Font()
        {
            FontFamily = "Arial",
            FontSize = 16
        }
    };
    
    // Create paragraph and add the styled text
    Paragraph paragraph = new Paragraph();
    paragraph.AddText(text);
    
    // Add paragraph to document and save
    doc.AddParagraph(paragraph);
    doc.SaveAs("styled.docx");
  3. 部署到您的生产环境中进行测试

    立即开始在您的项目中使用 IronWord,免费试用!
    arrow pointer

如何在 DOCX 中添加文本样式?

在 IronWord 中应用文本样式非常简单。 创建一个WordDocument对象,然后创建一个TextContent对象并传入你的文本。 使用IsBoldColorTextFont等属性应用TextStyle,并使用下划线或删除线等选项增强样式。

风格化后,将文本添加到 Paragraph 中,将段落插入到文档中,然后保存结果。 这种方法可对文本格式进行编程控制,适用于需要一致样式的自动文档生成场景。

:path=/static-assets/word/content-code-examples/how-to/add-style-text-simple.cs
using IronWord;

// Load docx
WordDocument doc = new WordDocument("sample.docx");

// Configure text
TextContent text = new TextContent();
text.Text = "Add text using IronWord";

// Configure text style settings
text.Style = new TextStyle()
{
    TextFont = new Font()
    {
        FontFamily = "Calibri", // Text Font is "Calibri"
        FontSize = 24, // Text Size is 24
    },
    Color = Color.Red, // Set text color to red
    IsBold = true,     // Make text bold
    IsItalic = true,   // Make text italic
	Underline = new Underline(), // Have an underline
    Strike = StrikeValue.DoubleStrike, // No strike-through
};

Paragraph paragraph = new Paragraph();

// Add text to paragraph
paragraph.AddText(text);

// Add paragraph to document
doc.AddParagraph(paragraph);

// Save document
doc.SaveAs("add-text-style.docx");
Imports IronWord

' Load docx
Dim doc As New WordDocument("sample.docx")

' Configure text
Dim text As New TextContent()
text.Text = "Add text using IronWord"

' Configure text style settings
text.Style = New TextStyle() With {
    .TextFont = New Font() With {
        .FontFamily = "Calibri", ' Text Font is "Calibri"
        .FontSize = 24 ' Text Size is 24
    },
    .Color = Color.Red, ' Set text color to red
    .IsBold = True, ' Make text bold
    .IsItalic = True, ' Make text italic
    .Underline = New Underline(), ' Have an underline
    .Strike = StrikeValue.DoubleStrike ' No strike-through
}

Dim paragraph As New Paragraph()

' Add text to paragraph
paragraph.AddText(text)

' Add paragraph to document
doc.AddParagraph(paragraph)

' Save document
doc.SaveAs("add-text-style.docx")
$vbLabelText   $csharpLabel

这将产生什么输出?

显示布局功能区和文档的 Microsoft Word 界面,其中应用了红色删除线文本格式

TextStyle 类提供了基本的格式选项,包括字体属性、文本颜色、粗体、斜体和下划线。该示例演示了如何将多种样式属性结合起来,创建格式丰富的文本。


我可以添加哪些特定样式?

如何更改文本颜色?

TextStyle 中的 Color 属性使用 IronWord.Models.Color 中的预定义颜色或自定义十六进制值设置文本颜色。 这样可以强调特定内容或与品牌色彩相匹配。 IronWord 支持多种颜色,包括红色、蓝色、绿色、橄榄色、深蓝色和栗色。

:path=/static-assets/word/content-code-examples/how-to/add-style-text-add-text.cs
using IronWord;

// Create document
WordDocument doc = new WordDocument();

// Add colored text
TextContent text = new TextContent("This text is olive-colored!");
text.Style = new TextStyle()
{
    Color = IronWord.Models.Color.Olive // defining text to be colored olive
};

Paragraph paragraph = new Paragraph();
paragraph.AddText(text);
doc.AddParagraph(paragraph);

// Save document
doc.SaveAs("colored-text.docx");
Imports IronWord

' Create document
Dim doc As New WordDocument()

' Add colored text
Dim text As New TextContent("This text is olive-colored!")
text.Style = New TextStyle() With {
    .Color = IronWord.Models.Color.Olive ' defining text to be colored olive
}

Dim paragraph As New Paragraph()
paragraph.AddText(text)
doc.AddParagraph(paragraph)

' Save document
doc.SaveAs("colored-text.docx")
$vbLabelText   $csharpLabel

彩色文本看起来像什么?

Microsoft Word 显示橄榄色文本格式,主页选项卡功能区显示字体和段落工具

如何设置字体家族和大小?

使用TextFont属性自定义文本外观。 将FontFamily设置为任何已安装的字体名称(例如,"Arial"、"Times New Roman"),并将FontSize为磅。 这样可以建立视觉层次,确保在不同设备和平台上的可读性。

:path=/static-assets/word/content-code-examples/how-to/add-style-text-add-font.cs
using IronWord;

// Create document
WordDocument doc = new WordDocument();

// Add text with custom font family and size
TextContent text = new TextContent("This text uses Arial at 24pt!");
text.Style = new TextStyle()
{
    TextFont = new IronWord.Models.Font()
    {
        FontFamily = "Arial",  // Set font family
        FontSize = 24          // Set font size in points
    }
};

Paragraph paragraph = new Paragraph();
paragraph.AddText(text);
doc.AddParagraph(paragraph);

// Save document
doc.SaveAs("font-styled-text.docx");
Imports IronWord

' Create document
Dim doc As New WordDocument()

' Add text with custom font family and size
Dim text As New TextContent("This text uses Arial at 24pt!")
text.Style = New TextStyle() With {
    .TextFont = New IronWord.Models.Font() With {
        .FontFamily = "Arial",  ' Set font family
        .FontSize = 24          ' Set font size in points
    }
}

Dim paragraph As New Paragraph()
paragraph.AddText(text)
doc.AddParagraph(paragraph)

' Save document
doc.SaveAs("font-styled-text.docx")
$vbLabelText   $csharpLabel

自定义字体样式看起来像什么?

Microsoft Word 显示工具栏中选择的 24pt Arial 字体,并显示格式化的示例文本

如何使文本加粗?

IsBold 属性设置为 true 以将文本加粗。 粗体文字通常用于标题、强调或突出重要信息。 结合其他样式属性,粗体文字可创建视觉层次并提高可读性。

:path=/static-assets/word/content-code-examples/how-to/add-style-text-add-bold.cs
using IronWord;

// Create document
WordDocument doc = new WordDocument();

// Add bold text
TextContent text = new TextContent("this is bold!");
text.Style = new TextStyle()
{
    IsBold = true  // Make text bold
};

Paragraph paragraph = new Paragraph();
paragraph.AddText(text);
doc.AddParagraph(paragraph);

// Save document
doc.SaveAs("bold-text.docx");
Imports IronWord

' Create document
Dim doc As New WordDocument()

' Add bold text
Dim text As New TextContent("this is bold!")
text.Style = New TextStyle() With {
    .IsBold = True ' Make text bold
}

Dim paragraph As New Paragraph()
paragraph.AddText(text)
doc.AddParagraph(paragraph)

' Save document
doc.SaveAs("bold-text.docx")
$vbLabelText   $csharpLabel

粗体文本看起来像什么?

显示粗体文本格式的 Microsoft Word 界面,文档中显示'这是粗体!'文本

如何使文本为斜体?

IsItalic 属性设置为 true 以获得斜体样式。 斜体字通常用于强调、标题、外来词或技术术语。 这种微妙的格式化既能区分文本元素,又不会产生粗体格式化的视觉效果。

:path=/static-assets/word/content-code-examples/how-to/add-style-text-add-italic.cs
using IronWord;

// Create document
WordDocument doc = new WordDocument();

// Add italic text
TextContent text = new TextContent("this is italic.");
text.Style = new TextStyle()
{
    IsItalic = true  // Make text italic
};

Paragraph paragraph = new Paragraph();
paragraph.AddText(text);
doc.AddParagraph(paragraph);

// Save document
doc.SaveAs("italic-text.docx");
Imports IronWord

' Create document
Dim doc As New WordDocument()

' Add italic text
Dim text As New TextContent("this is italic.")
text.Style = New TextStyle() With {
    .IsItalic = True  ' Make text italic
}

Dim paragraph As New Paragraph()
paragraph.AddText(text)
doc.AddParagraph(paragraph)

' Save document
doc.SaveAs("italic-text.docx")
$vbLabelText   $csharpLabel

斜体文本看起来像什么?

Word文档显示斜体文本,带状界面中的主选项卡格式选项可见

可用的样式属性有哪些?

IronWord 提供了全面的样式属性,与 Microsoft Word 的格式选项如出一辙。 这些特性结合在一起,形成了符合专业文档标准的复杂文本格式。

风格设计方法 说明 范例
`文本字体` 使用 `字体对象自定义文本外观,以点为单位设置字体家族和大小。 text.Style.TextFont = new Font() { FontFamily = "Calibri", FontSize = 24 };`
`颜色` 使用 `IronWord.Models.Color 中的预定义颜色或自定义十六进制值设置文本颜色。 text.Style.Color = IronWord.Models.Color.Red;`
`IsBold` 设置为`true时,文本将加粗,常用于标题或强调。 text.Style.IsBold = true;`
`IsItalic` 设置为`true时,文本将应用斜体样式,通常用于强调或标题。 text.Style.IsItalic = true;`
`下划线` 使用具有各种下划线样式的 `下划线` 对象为文本添加下划线。 text.Style.Underline = new Underline();`
`Strike` 使用 `StrikeValue枚举(Strike 或 DoubleStrike)对文本应用删除线。 text.Style.Strike = StrikeValue.Strike;`
`大写` 对文本应用大写效果,将所有字符转换为大写显示。 `text.Style.Caps = true;`
`字符量表` 按字符正常大小的百分比调整字符的宽度比例。 `text.Style.CharacterScale = 150;`
`Emboss` 将浮雕效果应用于文本,创造出凸起的外观。 `text.Style.Emboss = true;`
`重点` 使用 `EmphasisMarkValues 枚举值为样式文本添加强调标记。 text.Style.Emphasis = EmphasisMarkValues.Dot;`
`行距` 使用 `行距`对象控制文本行间距,以提高可读性。 `text.Style.LineSpacing = new LineSpacing() { Value = 1.5 };`
`大纲` 以轮廓效果渲染文本,仅显示字符边界。 `text.Style.Outline=true;`
`着色` 使用 `着色`对象为文本应用背景颜色或阴影。 `text.Style.Shading = new Shading() { Color = Color.Yellow };`
`小帽子` 将小写字母转换为小写字母,同时保持大小写的区别。 `text.Style.SmallCaps = true;`
`垂直位置` 调整文本相对于基线的垂直位置,以点为单位。 `text.Style.VerticalPosition = 5.0;`
`垂直文本对齐` 使用 `VerticalPositionValues枚举在其容器中垂直定位文本。 text.Style.VerticalTextAlignment = VerticalPositionValues.Superscript;`

组合多种样式

IronWord 的文本样式功能来自于结合多个属性来实现复杂的格式化。 下面是一个通过结合各种样式属性演示专业样式文本的示例:

using IronWord;
using IronWord.Models;

// Create a new document
WordDocument doc = new WordDocument();

// Create richly formatted text
TextContent headerText = new TextContent("Professional Document Header");
headerText.Style = new TextStyle()
{
    TextFont = new Font()
    {
        FontFamily = "Georgia",
        FontSize = 28
    },
    Color = Color.DarkBlue,
    IsBold = true,
    SmallCaps = true,
    Underline = new Underline(),
    CharacterScale = 110,  // Slightly expand character width
    Shading = new Shading() 
    { 
        Color = Color.LightGray  // Light background
    }
};

// Add header to document
Paragraph headerParagraph = new Paragraph();
headerParagraph.AddText(headerText);
doc.AddParagraph(headerParagraph);

// Create body text with different styling
TextContent bodyText = new TextContent("This is professionally formatted body text with custom styling.");
bodyText.Style = new TextStyle()
{
    TextFont = new Font()
    {
        FontFamily = "Calibri",
        FontSize = 11
    },
    Color = Color.Black,
    LineSpacing = new LineSpacing() { Value = 1.15 }  // Slightly increased line spacing
};

Paragraph bodyParagraph = new Paragraph();
bodyParagraph.AddText(bodyText);
doc.AddParagraph(bodyParagraph);

// Save the document
doc.SaveAs("professional-document.docx");
using IronWord;
using IronWord.Models;

// Create a new document
WordDocument doc = new WordDocument();

// Create richly formatted text
TextContent headerText = new TextContent("Professional Document Header");
headerText.Style = new TextStyle()
{
    TextFont = new Font()
    {
        FontFamily = "Georgia",
        FontSize = 28
    },
    Color = Color.DarkBlue,
    IsBold = true,
    SmallCaps = true,
    Underline = new Underline(),
    CharacterScale = 110,  // Slightly expand character width
    Shading = new Shading() 
    { 
        Color = Color.LightGray  // Light background
    }
};

// Add header to document
Paragraph headerParagraph = new Paragraph();
headerParagraph.AddText(headerText);
doc.AddParagraph(headerParagraph);

// Create body text with different styling
TextContent bodyText = new TextContent("This is professionally formatted body text with custom styling.");
bodyText.Style = new TextStyle()
{
    TextFont = new Font()
    {
        FontFamily = "Calibri",
        FontSize = 11
    },
    Color = Color.Black,
    LineSpacing = new LineSpacing() { Value = 1.15 }  // Slightly increased line spacing
};

Paragraph bodyParagraph = new Paragraph();
bodyParagraph.AddText(bodyText);
doc.AddParagraph(bodyParagraph);

// Save the document
doc.SaveAs("professional-document.docx");
Imports IronWord
Imports IronWord.Models

' Create a new document
Dim doc As New WordDocument()

' Create richly formatted text
Dim headerText As New TextContent("Professional Document Header")
headerText.Style = New TextStyle() With {
    .TextFont = New Font() With {
        .FontFamily = "Georgia",
        .FontSize = 28
    },
    .Color = Color.DarkBlue,
    .IsBold = True,
    .SmallCaps = True,
    .Underline = New Underline(),
    .CharacterScale = 110,  ' Slightly expand character width
    .Shading = New Shading() With {
        .Color = Color.LightGray  ' Light background
    }
}

' Add header to document
Dim headerParagraph As New Paragraph()
headerParagraph.AddText(headerText)
doc.AddParagraph(headerParagraph)

' Create body text with different styling
Dim bodyText As New TextContent("This is professionally formatted body text with custom styling.")
bodyText.Style = New TextStyle() With {
    .TextFont = New Font() With {
        .FontFamily = "Calibri",
        .FontSize = 11
    },
    .Color = Color.Black,
    .LineSpacing = New LineSpacing() With {.Value = 1.15}  ' Slightly increased line spacing
}

Dim bodyParagraph As New Paragraph()
bodyParagraph.AddText(bodyText)
doc.AddParagraph(bodyParagraph)

' Save the document
doc.SaveAs("professional-document.docx")
$vbLabelText   $csharpLabel

这种全面的样式设计方法创建的文档在整个应用程序的文档生成过程中都能保持一致的品牌和专业外观。

常见问题解答

如何用 C# 编程将文本格式应用于 Word 文档?

通过 IronWord 的 TextStyle 类,您可以应用专业的文本格式,包括字体、颜色、粗体、斜体和下划线。只需创建一个包含文本的 TextContent 对象,应用具有所需属性的 TextStyle,将其添加到段落中,然后保存文档即可。

在 DOCX 文件中为文本添加样式的基本步骤是什么?

使用 IronWord 创建文本样式的方法如下:1)通过 NuGet 安装 IronWord;2)创建 WordDocument 对象;3)创建包含文本的 TextContent;4)应用 TextStyle 属性,如字体、颜色或粗体;5)将文本添加到段落中并保存。

有哪些文本格式选项?

IronWord 的 TextStyle 类提供了基本的格式选项,包括字体属性(FontFamily 和 FontSize)、文本颜色、粗体、斜体、下划线和删除线。这些选项可以组合使用,以创建格式丰富的文本。

如何更改文本的字体系列和大小?

使用 TextStyle 中的 TextFont 属性指定字体家族和大小。将 FontFamily 设置为 "Arial "或 "Times New Roman "等字体,并将 FontSize 设置为所需的点大小,如较大的文本设置为 16。

我可以同时应用多种文本样式吗?

是的,IronWord 允许您在单个 TextStyle 对象中组合多个样式属性。您可以同时应用粗体、斜体、颜色和字体变化来创建复杂的文本格式。

如何使用 C# 更改 Word 文档中的文本颜色?

通过 IronWord TextStyle 中的 Color 属性,您可以使用 IronWord.Models.Color 中的预定义颜色或自定义十六进制值来设置文本颜色。该功能有助于在文档中强调特定内容或匹配品牌颜色。

Ahmad Sohail
全栈开发者

Ahmad 是一名全栈开发人员,拥有扎实的 C#、Python 和 Web 技术基础。他对构建可扩展的软件解决方案深感兴趣,并喜欢探索设计和功能在实际应用中如何结合。

在加入 Iron Software 团队之前,Ahmad 致力于自动化项目和 API 集成,专注于提高性能和开发人员体验。

在业余时间,他喜欢尝试 UI/UX 想法,贡献开源工具,并偶尔从事技术写作和文档工作,以便让复杂主题更易于理解。

准备开始了吗?
Nuget 下载 32,629 | 版本: 2026.2 刚刚发布