C# Word中設定/更改文本方向
一般情況下在Word中輸入的文字都是橫向的,今天給大家分享兩種方法來設定/更改一個section内的所有文本的方向及部分文本的方向,有興趣的朋友可以試下。
首先,從
https://visualstudiogallery.msdn.microsoft.com/d3a38f74-3490-42da-bdb0-37fa5acebc36下載下傳免費版.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);
}
}
}