Настройки выравнивания
Настройка настроек выравнивания
Настройки выравнивания в Microsoft Excel
Любой, кто использовал Microsoft Excel для форматирования ячеек, будет знаком с настройками выравнивания в Microsoft Excel.
Как видно на приведенной выше фигуре, существуют различные варианты выравнивания:
- Выравнивание текста (горизонтальное и вертикальное)
- Отступ.
- Ориентация.
- Управление текстом.
- Направление текста.
Все эти настройки выравнивания полностью поддерживаются Aspose.Cells и обсуждаются более подробно ниже.
Настройки выравнивания в Aspose.Cells
Aspose.Cells предоставляет класс Workbook, который представляет собой файл Excel. Класс Workbook содержит коллекцию Worksheets, которая позволяет получить доступ к каждому листу в файле Excel. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию Cells. Каждый элемент в коллекции Cells представляет объект класса Cell.
Aspose.Cells предоставляет методы GetStyle и SetStyle для класса Cell, которые используются для получения и установки форматирования ячейки. Класс Style предоставляет полезные свойства для настройки настроек выравнивания.
Выберите любой тип выравнивания текста, используя перечисление TextAlignmentType. Предопределенные типы выравнивания текста в перечислении TextAlignmentType следующие:
Типы выравнивания текста | Описание |
---|---|
Bottom | Представляет выравнивание текста по нижнему краю |
Center | Представляет выравнивание текста по центру |
CenterAcross | Представляет выравнивание текста по центру с наложением |
Distributed | Представляет распределенное выравнивание текста |
Fill | Представляет выравнивание текста по заливке |
General | Представляет общее выравнивание текста |
Justify | Представляет выравнивание текста по ширине |
Left | Представляет выравнивание текста влево |
Right | Представляет выравнивание текста вправо |
Top | Представляет верхнее выравнивание текста |
JustifiedLow | Выравнивает текст с настройкой длины кашиды для арабского текста. |
ThaiDistributed | Распределяет текст на тайском, поскольку каждый символ рассматривается как слово. |
Горизонтальное выравнивание
Используйте свойство HorizontalAlignment объекта Style для горизонтального выравнивания текста.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
style.HorizontalAlignment = TextAlignmentType.Center; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Вертикальное выравнивание
Аналогично горизонтальному выравниванию, используйте свойство VerticalAlignment объекта Style для вертикального выравнивания текста.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Clearing all the worksheets | |
workbook.Worksheets.Clear(); | |
// Adding a new worksheet to the Excel object | |
int i = workbook.Worksheets.Add(); | |
// Obtaining the reference of the newly added worksheet by passing its sheet index | |
Worksheet worksheet = workbook.Worksheets[i]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Setting the vertical alignment of the text in a cell | |
style.VerticalAlignment = TextAlignmentType.Center; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Отступ
Возможно установить уровень отступа текста в ячейке с помощью свойства IndentLevel объекта Style.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Setting the indentation level of the text (inside the cell) to 2 | |
style.IndentLevel = 2; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Ориентация
Установите ориентацию (поворот) текста в ячейке с помощью свойства RotationAngle объекта Style.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Setting the rotation of the text (inside the cell) to 25 | |
style.RotationAngle = 25; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Управление текстом
В следующем разделе рассматривается управление текстом с помощью установки переноса текста, уменьшения для подгонки и других параметров форматирования.
Перенос текста
Перенос текста в ячейке облегчает его чтение: высота ячейки подстраивается под весь текст, вместо его обрезки или выливания в смежные ячейки. Установите включение или отключение переноса текста с помощью свойства IsTextWrapped объекта Style.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create Workbook Object | |
Workbook wb = new Workbook(); | |
// Open first Worksheet in the workbook | |
Worksheet ws = wb.Worksheets[0]; | |
// Get Worksheet Cells Collection | |
Aspose.Cells.Cells cell = ws.Cells; | |
// Increase the width of First Column Width | |
cell.SetColumnWidth(0, 35); | |
// Increase the height of first row | |
cell.SetRowHeight(0, 36); | |
// Add Text to the Firts Cell | |
cell[0, 0].PutValue("I am using the latest version of Aspose.Cells to test this functionality"); | |
// Make Cell's Text wrap | |
Style style = cell[0, 0].GetStyle(); | |
style.IsTextWrapped = true; | |
cell[0, 0].SetStyle(style); | |
// Save Excel File | |
wb.Save(dataDir+ "WrappingText.out.xlsx"); |
Уменьшение для подгонки
Вариантом для переноса текста в поле является уменьшение размера текста для вписывания его в размеры ячейки. Это делается путем установки свойства IsTextWrapped объекта Style в true.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Aspose.Cells.Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Shrinking the text to fit according to the dimensions of the cell | |
style.ShrinkToFit = true; | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Объединение ячеек
Как и в Microsoft Excel, Aspose.Cells поддерживает объединение нескольких ячеек в одну. Aspose.Cells предоставляет два подхода к этой задаче. Один из способов - вызвать метод коллекции Cells Merge. Метод Merge принимает следующие параметры для объединения ячеек:
- Первая строка: первая строка, с которой начинается объединение.
- Первая колонка: первая колонка, с которой начинается объединение.
- Количество строк: количество строк для объединения.
- Количество столбцов: количество столбцов для объединения.
// 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 = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Create a Workbook. | |
Workbook wbk = new Workbook(); | |
// Create a Worksheet and get the first sheet. | |
Worksheet worksheet = wbk.Worksheets[0]; | |
// Create a Cells object ot fetch all the cells. | |
Cells cells = worksheet.Cells; | |
// Merge some Cells (C6:E7) into a single C6 Cell. | |
cells.Merge(5, 2, 2, 3); | |
// Input data into C6 Cell. | |
worksheet.Cells[5, 2].PutValue("This is my value"); | |
// Create a Style object to fetch the Style of C6 Cell. | |
Style style = worksheet.Cells[5, 2].GetStyle(); | |
// Create a Font object | |
Font font = style.Font; | |
// Set the name. | |
font.Name = "Times New Roman"; | |
// Set the font size. | |
font.Size = 18; | |
// Set the font color | |
font.Color = System.Drawing.Color.Blue; | |
// Bold the text | |
font.IsBold = true; | |
// Make it italic | |
font.IsItalic = true; | |
// Set the backgrond color of C6 Cell to Red | |
style.ForegroundColor = System.Drawing.Color.Red; | |
style.Pattern = BackgroundType.Solid; | |
// Apply the Style to C6 Cell. | |
cells[5, 2].SetStyle(style); | |
// Save the Workbook. | |
wbk.Save(dataDir + "mergingcells.out.xls"); |
Другой способ - сначала вызвать метод коллекции Cells для создания диапазона ячеек, которые будут объединены. Метод CreateRange принимает тот же набор параметров, что и метод Merge, обсуждаемый выше, и возвращает объект Range. Объект Range также предоставляет метод Merge, который объединяет диапазон, указанный в объекте Range.
Направление текста
Можно установить порядок чтения текста в ячейках. Порядок чтения - это визуальный порядок, в котором отображаются символы, слова и т. д. Например, английский язык - это язык слева направо, а арабский язык - это язык справа налево.
Порядок чтения задается свойством TextDirection объекта Style. Aspose.Cells предоставляет предопределенные типы направления текста в перечислении TextDirectionType.
** Типы направления текста ** | ** Описание ** |
---|---|
Context | Порядок чтения согласуется с языком первого введенного символа |
LeftToRight | Порядок чтения слева направо |
RightToLeft | Порядок чтения справа налево |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of first worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("I am using the latest version of Aspose.Cells to test this functionality."); | |
// Gets style in the "A1" cell | |
Style style = cell.GetStyle(); | |
// Shrinking the text to fit according to the dimensions of the cell | |
style.TextDirection = (TextDirectionType.LeftToRight); | |
cell.SetStyle(style); | |
// Saving the Excel file | |
workbook.Save("book1.xlsx"); |