当前位置: 移动技术网 > IT编程>开发语言>c# > C# 向Word中设置/更改文本方向的方法(两种)

C# 向Word中设置/更改文本方向的方法(两种)

2019年07月18日  | 移动技术网IT编程  | 我要评论

一般情况下在word中输入的文字都是横向的,今天给大家分享两种方法来设置/更改一个section内的所有文本的方向及部分文本的方向,有兴趣的朋友可以试下。

首先,从下载免费版.net word类库并安装,然后创建一个c# 控制台应用程序,添加引用及命名空间并参考以下步骤。

步骤1:创建一个新的document对象并加载word文档。

document document = new document();
document.loadfromfile("示例.docx"); 

步骤2:为一个section内的所有文本设置文本方向。

//获取第一个section并为其设置文本方向
section section = document.sections[0];
section.textdirection = textdirection.righttoleftrotated; 

如果要设置部分文本的文本方向,可以将该文本放在table中然后再设置文本方向,如以下步骤:

步骤3:添加一个新的section和一个table,获取目标单元格并设置文本方向,然后将文本添加到单元格。

//添加一个新的section到文档
section sec = document.addsection();
//添加一个table到该section
table table = sec.addtable();
//添加一行和一列到table
table.resetcells(1, 1);
//获取单元格
tablecell cell = table.rows[0].cells[0];
table.rows[0].height = 50;
table.rows[0].cells[0].width = 5;
//设置单元格的文本方向并添加文本到该单元格
cell.cellformat.textdirection = textdirection.righttoleftrotated;
cell.addparagraph().appendtext("你好"); 

添加一个新的段落来检测以上方法是否会影响该section内的其他文本的文本方向:

sec.addparagraph().appendtext("新段落"); 

步骤4:保存文档。

document.savetofile("文本方向.docx", fileformat.docx);

运行结果:

设置一个section内的所有文本的文本方向:

设置部分文本的文本方向:

全部代码:

using spire.doc;
using spire.doc.documents;
namespace set_text_direction_in_word
{
class program
{
static void main(string[] args)
{
document document = new document();
document.loadfromfile("示例.docx");
//设置一个section内的所有文本的文本方向
section section = document.sections[0];
section.textdirection = textdirection.righttoleftrotated; 
//设置部分文本的文本方向
section sec = document.addsection();
table table = sec.addtable();
table.resetcells(1, 1);
tablecell cell = table.rows[0].cells[0];
table.rows[0].height = 50;
table.rows[0].cells[0].width = 5;
cell.cellformat.textdirection = textdirection.righttoleftrotated;
cell.addparagraph().appendtext("你好");
sec.addparagraph().appendtext("新段落");
//保存文档
document.savetofile("文本方向.docx", fileformat.docx);
}
}
}

以上所述是小编给大家介绍的c# 向word中设置/更改文本方向的方法(两种),希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网