Настройки выравнивания
Настройка настроек выравнивания
Настройки выравнивания в Microsoft Excel
Любой, кто использовал Microsoft Excel для форматирования ячеек, будет знаком с настройками выравнивания в Microsoft Excel.
Как видно на приведенной выше фигуре, существуют различные варианты выравнивания:
- Выравнивание текста (горизонтальное и вертикальное)
- Отступ.
- Ориентация.
- Управление текстом.
- Направление текста.
Все эти настройки выравнивания полностью поддерживаются Aspose.Cells для Python via .NET и подробно обсуждаются ниже.
Настройки выравнивания в Aspose.Cells для Python via .NET
Aspose.Cells для Python via .NET предоставляет класс, Workbook, который представляет файл Excel. Класс Workbook содержит коллекцию worksheets, которая позволяет получать доступ к каждому листу Excel. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию cells. Каждый элемент в коллекции cells представляет объект класса Cell.
Aspose.Cells для Python via .NET предоставляет методы get_style и set_style для класса Cell, используемые для получения и установки формата ячейки. Класс Style предоставляет полезные свойства для настройки параметров выравнивания.
Выберите любой тип выравнивания текста, используя перечисление TextAlignmentType. Предопределенные типы выравнивания текста в перечислении TextAlignmentType следующие:
Типы выравнивания текста | Описание |
---|---|
GENERAL | Представляет общий текстовый выравнивание |
BOTTOM | Представляет нижнее выравнивание текста |
CENTER | Представляет центрирование текста |
CENTER_ACROSS | Представляет выравнивание по центру через ячейки |
DISTRIBUTED | Представляет распределенное выравнивание текста |
FILL | Представляет заливку текста |
JUSTIFY | Представляет оправданное выравнивание текста |
LEFT | Обозначает выравнивание текста по левому краю |
RIGHT | Обозначает выравнивание текста по правому краю |
TOP | Обозначает выравнивание текста по верхнему краю |
JUSTIFIED_LOW | Выравнивает текст с учетом скорректированной длины кашиды для арабского текста |
THAI_DISTRIBUTED | Специально распределяет тайский текст, потому что каждый символ считается словом |
Горизонтальное выравнивание
Используйте свойство horizontal_alignment объекта Style для горизонтального выравнивания текста.
from aspose.cells import SaveFormat, TextAlignmentType, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Вертикальное выравнивание
Аналогично горизонтальному выравниванию, используйте свойство vertical_alignment объекта Style для вертикального выравнивания текста.
from aspose.cells import SaveFormat, TextAlignmentType, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Clearing all the worksheets | |
workbook.worksheets.clear() | |
# Adding a new worksheet to the Excel object | |
i = workbook.worksheets.add() | |
# Obtaining the reference of the newly added worksheet by passing its sheet index | |
worksheet = workbook.worksheets[i] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Setting the vertical alignment of the text in a cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Отступ
Возможно установить уровень отступа текста в ячейке с помощью свойства indent_level объекта Style.
from aspose.cells import SaveFormat, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Setting the indentation level of the text (inside the cell) to 2 | |
style.indent_level = 2 | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Ориентация
Установите ориентацию (поворот) текста в ячейке с помощью свойства rotation_angle объекта Style.
from aspose.cells import SaveFormat, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Setting the rotation of the text (inside the cell) to 25 | |
style.rotation_angle = 25 | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Управление текстом
В следующем разделе рассматривается управление текстом с помощью установки переноса текста, уменьшения для подгонки и других параметров форматирования.
Перенос текста
Перенос текста в ячейке облегчает его чтение: высота ячейки подстраивается под весь текст, вместо его обрезки или выливания в смежные ячейки. Установите включение или отключение переноса текста с помощью свойства is_text_wrapped объекта Style.
from aspose.cells import Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create Workbook Object | |
wb = Workbook() | |
# Open first Worksheet in the workbook | |
ws = wb.worksheets[0] | |
# Get Worksheet Cells Collection | |
cell = ws.cells | |
# Increase the width of First Column Width | |
cell.set_column_width(0, 35) | |
# Increase the height of first row | |
cell.set_row_height(0, 36) | |
# Add Text to the Firts Cell | |
cell.get(0, 0).put_value("I am using the latest version of Aspose.Cells to test this functionality") | |
# Make Cell's Text wrap | |
style = cell.get(0, 0).get_style() | |
style.is_text_wrapped = True | |
cell.get(0, 0).set_style(style) | |
# Save Excel File | |
wb.save(dataDir + "WrappingText.out.xlsx") |
Уменьшение для подгонки
Вариантом для переноса текста в поле является уменьшение размера текста для вписывания его в размеры ячейки. Это делается путем установки свойства is_text_wrapped объекта Style в true.
from aspose.cells import SaveFormat, Workbook | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("Visit Aspose!") | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style = cell.get_style() | |
# Shrinking the text to fit according to the dimensions of the cell | |
style.shrink_to_fit = True | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls", SaveFormat.EXCEL_97_TO_2003) |
Объединение ячеек
Как Microsoft Excel, Aspose.Cells для Python via .NET поддерживает объединение нескольких ячеек в одну. Aspose.Cells для Python via .NET предлагает два способа выполнения этой задачи. Один способ — вызвать метод merge коллекции cells. Метод merge принимает следующие параметры для объединения ячеек:
- Первая строка: первая строка, с которой начинается объединение.
- Первая колонка: первая колонка, с которой начинается объединение.
- Количество строк: количество строк для объединения.
- Количество столбцов: количество столбцов для объединения.
from aspose.cells import BackgroundType, Workbook | |
from aspose.pydrawing import Color | |
from os import os, path | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# The path to the documents directory. | |
dataDir = RunExamples.GetDataDir(".") | |
# Create directory if it is not already present. | |
IsExists = path.isdir(dataDir) | |
if notIsExists: | |
os.makedirs(dataDir) | |
# Create a Workbook. | |
wbk = Workbook() | |
# Create a Worksheet and get the first sheet. | |
worksheet = wbk.worksheets[0] | |
# Create a Cells object ot fetch all the 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.get(5, 2).put_value("This is my value") | |
# Create a Style object to fetch the Style of C6 Cell. | |
style = worksheet.cells.get(5, 2).get_style() | |
# Create a Font object | |
font = style.font | |
# Set the name. | |
font.name = "Times New Roman" | |
# Set the font size. | |
font.size = 18 | |
# Set the font color | |
font.color = Color.blue | |
# Bold the text | |
font.is_bold = True | |
# Make it italic | |
font.is_italic = True | |
# Set the backgrond color of C6 Cell to Red | |
style.foreground_color = Color.red | |
style.pattern = BackgroundType.SOLID | |
# Apply the Style to C6 Cell. | |
cells.get(5, 2).set_style(style) | |
# Save the Workbook. | |
wbk.save(dataDir + "mergingcells.out.xls") |
Другой способ - сначала вызвать метод коллекции cells для создания диапазона ячеек, которые будут объединены. Метод create_range принимает тот же набор параметров, что и метод merge, обсуждаемый выше, и возвращает объект Range. Объект Range также предоставляет метод merge, который объединяет диапазон, указанный в объекте Range.
Направление текста
Можно установить порядок чтения текста в ячейках. Порядок чтения - это визуальный порядок, в котором отображаются символы, слова и т. д. Например, английский язык - это язык слева направо, а арабский язык - это язык справа налево.
Порядок чтения устанавливается с помощью свойства text_direction объекта Style. Aspose.Cells для Python via .NET предоставляет предустановленные типы направления текста в перечислении TextDirectionType.
** Типы направления текста ** | ** Описание ** |
---|---|
CONTEXT | Порядок чтения соответствует языку первого введенного символа |
LEFT_TO_RIGHT | Порядок чтения слева направо |
RIGHT_TO_LEFT | Порядок чтения справа налево |
from aspose.cells import TextDirectionType, Workbook | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of first worksheet | |
worksheet = workbook.worksheets[0] | |
# Accessing the "A1" cell from the worksheet | |
cell = worksheet.cells.get("A1") | |
# Adding some value to the "A1" cell | |
cell.put_value("I am using the latest version of Aspose.Cells to test this functionality.") | |
# Gets style in the "A1" cell | |
style = cell.get_style() | |
# Shrinking the text to fit according to the dimensions of the cell | |
style.text_direction = TextDirectionType.LEFT_TO_RIGHT | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save("book1.xlsx") |