4

C#/VB.NET 设置Word文档段落缩进

 3 years ago
source link: https://blog.51cto.com/u_15656056/5640561
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C#/VB.NET 设置Word文档段落缩进

精选 原创

缩进是指调整文本与页面边界之间的距离。在水平标尺,有四个段落缩进滑块:首行缩进、悬挂缩进、左缩进以及右缩进。在对于word文档的录入时,常常需要注意录入的格式,通过合理地设置段落格式,可以让文稿看起来更加美观,也可以加快录入的速度。在本文中,将详细为您介绍如何通过C#/VB.NET设置Word文档段落缩进。下面是我整理的思路及具体步骤,并附上C#和VB.NET代码供大家参考。详情请阅读以下内容。

使用工具:​ ​Free Spire.Doc for .NET ​​(免费版)

程序环境

本次测试时,在程序中引入​ ​Free Spire.Doc for .NET​​。可通过以下方法引用Spire.Doc.dll文件:

方法1:将 Free Spire.Doc for .NET 下载到本地,解压,安装。安装完成后,找到安装路径下BIN文件夹中的Spire.Doc.dll。然后在Visual Studio中打开“解决方案资源管理器”,鼠标右键点击“引用”,“添加引用”,将本地路径BIN文件夹下的dll文件添加引用至程序。

方法2:通过 ​ ​NuGet​​ 安装。可通过以下2种方法安装:

(1)可以在Visual Studio中打开“解决方案资源管理器”,鼠标右键点击“引用”,“管理NuGet包”,然后搜索“Free Spire.Doc”,点击“安装”。等待程序安装完成。

(2)将以下内容复制到PM控制台安装。

Install-Package FreeSpire.Doc -Version 10.8.0

具体步骤

  • 创建一个Document实例。
  • 使用Document.LoadFromFile() 方法加载示例 Word 文档。
  • 使用Document.Sections() 属性获取指定部分。
  • 使用Section.Paragraphs() 属性获取指定段落。
  • 使用Paragraph.Format 属性获取段落格式,然后使用 ParagraphFormat 类的上面列出的属性设置段落缩进。
  • 使用Document.SaveToFile() 方法保存文档。

完整代码

【C#】

using Spire.Doc;
using Spire.Doc.Documents;

namespace WordIndent
{
class Program
{
static void Main(string[] args)
{
//创建一个Document实例。
Document doc = new Document();

//加载示例 Word 文档
doc.LoadFromFile("编程语言发展历程.docx");

//获取第一段并设置左缩进
Paragraph para1 = doc.Sections[0].Paragraphs[0];
para1.Format.LeftIndent = 30;

//获取第二段并设置右缩进
Paragraph para2 = doc.Sections[0].Paragraphs[1];
para2.Format.RightIndent = 30;

//获取第三段并设置首行缩进
Paragraph para3 = doc.Sections[0].Paragraphs[2];
para3.Format.FirstLineIndent = 30;

//获取第四段并设置悬挂缩进
Paragraph para4 = doc.Sections[0].Paragraphs[3];
para4.Format.FirstLineIndent = -30;

//保存文档
doc.SaveToFile("缩进文档.docx", FileFormat.Docx2010);
}
}
}

VB.NET​

Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordIndent
Friend Class Program
Private Shared Sub Main(ByVal args As String())
'创建一个Document实例。
Dim doc As Document = New Document()

'加载示例 Word 文档
doc.LoadFromFile("编程语言发展历程.docx")

'获取第一段并设置左缩进
Dim para1 As Paragraph = doc.Sections(0).Paragraphs(0)
para1.Format.LeftIndent = 30

'获取第二段并设置右缩进
Dim para2 As Paragraph = doc.Sections(0).Paragraphs(1)
para2.Format.RightIndent = 30

'获取第三段并设置首行缩进
Dim para3 As Paragraph = doc.Sections(0).Paragraphs(2)
para3.Format.FirstLineIndent = 30

'获取第四段并设置悬挂缩进
Dim para4 As Paragraph = doc.Sections(0).Paragraphs(3)
para4.Format.FirstLineIndent = -30

'保存文档
doc.SaveToFile("缩进文档.docx", FileFormat.Docx2010)
End Sub
End Class
End Namespace

效果图

C#/VB.NET 设置Word文档段落缩进_段落缩进

注意:测试代码中的文件路径为程序Debug路径,仅供参考,文件路径可自定义为其他路径。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK