Форматировать ячейки
Введение
Как форматировать ячейки с помощью методов GetStyle и SetStyle
Применить различные виды стилей форматирования на ячейки для установки цветов фона или переднего плана, границ, шрифтов, горизонтальных и вертикальных выравниваний, уровня отступа, направления текста, угла поворота и многое другое.
Как использовать методы GetStyle и SetStyle
Если разработчикам нужно применить различные стили форматирования к различным ячейкам, то лучше получить Style ячейки с помощью метода Cell.get_style, указать атрибуты стиля, а затем применить форматирование с помощью метода Cell.set_style. Приведен пример, демонстрирующий этот подход к применению различного форматирования к ячейке.
from aspose.cells import BorderType, CellBorderType, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the 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("Hello Aspose!") | |
# Get the style from A1 cell | |
style = cell.get_style() | |
# Setting the vertical alignment | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text | |
style.font.color = Color.green | |
# Setting to shrink according to the text contained in it | |
style.shrink_to_fit = True | |
# Setting the bottom border color to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Applying the style to A1 cell | |
cell.set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Как использовать объект стиля для форматирования различных ячеек
Если разработчикам нужно применить одинаковый стиль форматирования к различным ячейкам, то они могут использовать Style объект. Пожалуйста, выполните следующие шаги для использования объекта Style:
- Добавьте объект Style, вызвав метод create_style класса Workbook
- Получите только что добавленный объект Style
- Установите желаемые свойства/атрибуты объекта Style, чтобы применить желаемые настройки форматирования
- Присвойте настроенный объект Style вашим желаемым ячейкам
Этот подход может значительно повысить эффективность ваших приложений и сэкономить память.
from aspose.cells import BorderType, CellBorderType, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Adding a new worksheet to the Excel object | |
i = workbook.worksheets.add() | |
# Obtaining the reference of the first 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("Hello Aspose!") | |
# Adding a new Style | |
style = workbook.create_style() | |
# Setting the vertical alignment of the text in the "A1" cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text in the "A1" cell | |
style.font.color = Color.green | |
# Shrinking the text to fit in the cell | |
style.shrink_to_fit = True | |
# Setting the bottom border color of the cell to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type of the cell to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Assigning the Style object to the "A1" cell | |
cell.set_style(style) | |
# Apply the same style to some other cells | |
worksheet.cells.get("B1").set_style(style) | |
worksheet.cells.get("C1").set_style(style) | |
worksheet.cells.get("D1").set_style(style) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Как использовать предопределенные стили Microsoft Excel 2007
Если вам необходимо применять разные стили форматирования для Microsoft Excel 2007, используйте стили с помощью API Aspose.Cells for Python via .NET. Ниже приведен пример, демонстрирующий этот подход для применения предопределенного стиля к ячейке.
from aspose.cells import 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) | |
# Instantiate a new Workbook. | |
workbook = Workbook() | |
# Create a style object . | |
style = workbook.create_style() | |
# Input a value to A1 cell. | |
workbook.worksheets[0].cells.get("A1").put_value("Test") | |
# Apply the style to the cell. | |
workbook.worksheets[0].cells.get("A1").set_style(style) | |
# Save the Excel 2007 file. | |
workbook.save(dataDir + "book1.out.xlsx") |
Как форматировать выбранные символы в ячейке
Работа со настройками шрифта объясняет, как форматировать текст в ячейках, но это объясняет только, как форматировать весь содержимое ячейки. Что, если вы хотите отформатировать только выбранные символы?
Aspose.Cells for Python via .NET также поддерживает эту функцию. Эта тема объясняет, как эффективно использовать эту функцию.
Как форматировать выбранные символы
Aspose.Cells for Python via .NET предоставляет класс Workbook, который представляет файл Microsoft Excel. Класс Workbook содержит коллекцию worksheets, которая обеспечивает доступ к каждому листу в файле Excel. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию cells. Каждый элемент коллекции cells представляет объект класса Cell.
Класс Cell предоставляет метод characters, который принимает следующие параметры для выбора диапазона символов внутри ячейки:
- Индекс начала, индекс символа, с которого начинается выбор.
- Количество символов, количество выбираемых символов.
Метод characters возвращает экземпляр класса FontSetting, который позволяет разработчикам форматировать символы таким же образом, как они бы это сделали с ячейкой, как показано ниже в примере кода. В выходном файле в ячейке A1 слово ‘Visit’ будет отформатировано шрифтом по умолчанию, но ‘Aspose!’ будет жирным и синим.
from aspose.cells import 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the first(default) worksheet by passing its sheet index | |
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 font of selected characters to bold | |
cell.characters(6, 7).font.is_bold = True | |
# Setting the font color of selected characters to blue | |
cell.characters(6, 7).font.color = Color.blue | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Как форматировать строки и столбцы
Иногда разработчику требуется применить одно и то же форматирование на строки или столбцы. Применение форматирования к ячейкам одну за другой часто занимает больше времени и не является хорошим решением. Чтобы решить эту проблему, Aspose.Cells for Python via .NET предоставляет простой быстрый способ, подробно описанный в этой статье.
Форматирование строк и столбцов
Aspose.Cells for Python via .NET предоставляет класс Workbook, который представляет файл Microsoft Excel. Класс Workbook содержит коллекцию worksheets, которая обеспечивает доступ к каждому листу в Excel файле. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию cells. Коллекция cells содержит коллекцию rows.
Как форматировать строку
Каждый элемент в коллекции {0} представляет объект {1}. Объект {2} предлагает метод {3, используемый для установки форматирования строки. Для применения одного и того же форматирования к строке используйте объект {4}. Ниже приведены шаги, как его использовать.
- Добавьте объект Style в класс Workbook, вызвав его метод create_style.
- Установите свойства объекта Style, чтобы применить настройки форматирования.
- Включите соответствующие атрибуты для объекта StyleFlag.
- Назначьте настроенный объект Style на объект Row.
from aspose.cells import BorderType, CellBorderType, StyleFlag, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the first (default) worksheet by passing its sheet index | |
worksheet = workbook.worksheets[0] | |
# Adding a new Style to the styles | |
style = workbook.create_style() | |
# Setting the vertical alignment of the text in the "A1" cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text in the "A1" cell | |
style.font.color = Color.green | |
# Shrinking the text to fit in the cell | |
style.shrink_to_fit = True | |
# Setting the bottom border color of the cell to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type of the cell to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Creating StyleFlag | |
styleFlag = StyleFlag() | |
styleFlag.horizontal_alignment = True | |
styleFlag.vertical_alignment = True | |
styleFlag.shrink_to_fit = True | |
styleFlag.borders = True | |
styleFlag.font_color = True | |
# Accessing a row from the Rows collection | |
row = worksheet.cells.rows[0] | |
# Assigning the Style object to the Style property of the row | |
row.apply_style(style, styleFlag) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Как форматировать столбец
Коллекция cells также предоставляет коллекцию columns. Каждый элемент в коллекции columns представляет объект Column. Аналогично объекту Row, объект Column также предлагает метод apply_style для форматирования столбца.
from aspose.cells import BorderType, CellBorderType, StyleFlag, TextAlignmentType, 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) | |
# Instantiating a Workbook object | |
workbook = Workbook() | |
# Obtaining the reference of the first (default) worksheet by passing its sheet index | |
worksheet = workbook.worksheets[0] | |
# Adding a new Style to the styles | |
style = workbook.create_style() | |
# Setting the vertical alignment of the text in the "A1" cell | |
style.vertical_alignment = TextAlignmentType.CENTER | |
# Setting the horizontal alignment of the text in the "A1" cell | |
style.horizontal_alignment = TextAlignmentType.CENTER | |
# Setting the font color of the text in the "A1" cell | |
style.font.color = Color.green | |
# Shrinking the text to fit in the cell | |
style.shrink_to_fit = True | |
# Setting the bottom border color of the cell to red | |
style.borders.get(BorderType.BOTTOM_BORDER).color = Color.red | |
# Setting the bottom border type of the cell to medium | |
style.borders.get(BorderType.BOTTOM_BORDER).line_style = CellBorderType.MEDIUM | |
# Creating StyleFlag | |
styleFlag = StyleFlag() | |
styleFlag.horizontal_alignment = True | |
styleFlag.vertical_alignment = True | |
styleFlag.shrink_to_fit = True | |
styleFlag.borders = True | |
styleFlag.font_color = True | |
# Accessing a column from the Columns collection | |
column = worksheet.cells.columns[0] | |
# Applying the style to the column | |
column.apply_style(style, styleFlag) | |
# Saving the Excel file | |
workbook.save(dataDir + "book1.out.xls") |
Продвинутые темы
- Настройки выравнивания
- Настройки границ
- Установить условные форматы для файлов Excel и ODS.
- Темы и цвета Excel
- Настройки заливки
- Настройки шрифта
- Форматирование ячеек листа в книге Excel
- Реализация системы дат 1904 года
- Объединение и разъединение ячеек
- Настройки чисел
- Получение и установка стиля ячеек