如何对文本框应用/设置文本对齐

Contents
[ ]

文本框可以提高文档和图表的表现力,对文本框的不同部分应用不同的对齐方式可以帮助突出读者感兴趣的要点。但是文本框的默认对齐方式无法满足我们所有的需求。因此,您可能需要调整每个文本框以满足您的目标要求。如果您没有太多的文本框对象需要调整,那么您很幸运。如果有太多的文本框需要调整,那么您可能会遇到麻烦。现在不用担心,Aspose.Cells 提供了 API 接口来帮助您做到这一点。

以下示例代码将文本对齐应用于文本框。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = "";
if (!System.IO.Directory.Exists(dataDir))
{
System.IO.Directory.CreateDirectory(dataDir);
}
//Instantiating a Workbook object
Workbook workbook = new Workbook();
ShapeCollection shapes = workbook.Worksheets[0].Shapes;
//add a TextBox
Shape shape = shapes.AddTextBox(2, 0, 2, 0, 50, 120);
shape.Text = "This is a test.";
//set alignment
shape.TextHorizontalAlignment = TextAlignmentType.Center;
shape.TextVerticalAlignment = TextAlignmentType.Center;
//Save the excel file.
workbook.Save(dataDir + "result.xlsx");

您也可以使用适当的 HTML 文本更改文本框形状内的一些文本的文本对齐方式。以下示例代码将文本对齐应用于文本框内的部分文本。

源文件

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Intialize an object of the Workbook class to load template file
Workbook sourceWb = new Workbook("SampleTextboxExcel2016.xlsx");
// Access the target textbox whose text is to be aligned
var sourceTextBox = sourceWb.Worksheets[0].Shapes[0];
// Create and object of the target workbook
var destWb = new Workbook();
// Access first worksheet from the collection
var _sheet = destWb.Worksheets[0];
//Create new textbox
TextBox _textBox = (TextBox)_sheet.Shapes.AddShape( MsoDrawingType.TextBox,1, 0, 1, 0, 200, 200);
// Alternatively text box can be added using following line as well
// TextBox _textBox = _sheet.Shapes.AddTextBox(1, 0, 1, 0, 200, 200);
// Use Html string from a template file textbox
_textBox.HtmlText = sourceTextBox.HtmlText;
// Save the workbook on disc
destWb.Save("Output.xlsx");