Paramètres d alignement

Configuration des paramètres d’alignement

Paramètres d’alignement dans Microsoft Excel

Toute personne ayant utilisé Microsoft Excel pour formater des cellules sera familière avec les paramètres d’alignement dans Microsoft Excel.

Comme vous pouvez le voir sur la figure ci-dessus, il existe différents types d’options d’alignement :

  • Alignement du texte (horizontal et vertical)
  • Retrait.
  • Orientation.
  • Contrôle du texte.
  • Direction du texte.

Tous ces réglages d’alignement sont entièrement pris en charge par Aspose.Cells pour Python via .NET et sont discutés plus en détail ci-dessous.

Réglages d’alignement dans Aspose.Cells pour Python via .NET

Aspose.Cells pour Python via .NET fournit une classe, Workbook, qui représente un fichier Excel. La classe Workbook contient une collection worksheets qui permet d’accéder à chaque feuille de calcul dans le fichier Excel. Une feuille est représentée par la classe Worksheet. La classe Worksheet fournit une collection cells. Chaque élément de la collection cells représente un objet de la classe Cell.

Aspose.Cells pour Python via .NET fournit des méthodes get_style et set_style pour la classe Cell qui sont utilisées pour obtenir et définir la mise en forme d’une cellule. La classe Style offre des propriétés utiles pour configurer les réglages d’alignement.

Sélectionnez n’importe quel type d’alignement de texte en utilisant l’énumération TextAlignmentType. Les types d’alignement de texte prédéfinis dans l’énumération TextAlignmentType sont:

Types d’alignement de texte Description
GENERAL Représente un alignement de texte général
BOTTOM Représente un alignement du texte en bas
CENTER Représente un alignement du texte au centre
CENTER_ACROSS Représente un alignement du texte centré à travers
DISTRIBUTED Représente un alignement distribué du texte
FILL Représente un alignement du texte rempli
JUSTIFY Représente un alignement justifié du texte
LEFT Représente un alignement du texte à gauche
RIGHT Représente un alignement du texte à droite
TOP Représente un alignement du texte en haut
JUSTIFIED_LOW Aligne le texte avec une longueur de kasaida ajustée pour le texte arabe
THAI_DISTRIBUTED Distribue le texte thaï de manière spéciale, chaque caractère étant traité comme un mot

Alignement horizontal

Utilisez la propriété horizontal_alignment de l’objet Style pour aligner le texte horizontalement.

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)

Alignement vertical

Tout comme l’alignement horizontal, utilisez la propriété vertical_alignment de l’objet Style pour aligner le texte verticalement.

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)

Indentation

Il est possible de définir le niveau d’indentation du texte dans une cellule avec la propriété indent_level de l’objet 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)

Orientation

Définissez l’orientation (rotation) du texte dans une cellule avec la propriété rotation_angle de l’objet 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)

Contrôle du texte

La section suivante aborde comment contrôler le texte en définissant le retour à la ligne, le rétrécissement pour s’adapter et d’autres options de mise en forme.

Retour à la ligne du texte

Le retour à la ligne du texte dans une cellule facilite sa lecture : la hauteur de la cellule s’adapte pour contenir tout le texte, au lieu de le couper ou de le faire déborder dans les cellules adjacentes. Définissez le retour à la ligne sur ou hors avec la propriété is_text_wrapped de l’objet 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")
Rétrécissement pour s’adapter

Une option pour le retour à la ligne du texte dans un champ est de rétrécir la taille du texte pour s’adapter aux dimensions d’une cellule. Cela se fait en définissant la propriété is_text_wrapped de l’objet Style sur 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)
Fusion de cellules

Comme Microsoft Excel, Aspose.Cells pour Python via .NET supporte la fusion de plusieurs cellules en une seule. Aspose.Cells pour Python via .NET offre deux approches pour cette tâche. Une consiste à appeler la méthode merge de la collection cells. La méthode merge prend les paramètres suivants pour fusionner les cellules :

  • Première rangée : la première rangée à partir de laquelle commencer la fusion.
  • Première colonne : la première colonne à partir de laquelle commencer la fusion.
  • Nombre de rangées : le nombre de rangées à fusionner.
  • Nombre de colonnes : le nombre de colonnes à fusionner.
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")

L’autre façon consiste à appeler d’abord la méthode create_range de la cells collection pour créer une plage de cellules à fusionner. La méthode create_range prend le même ensemble de paramètres que la méthode merge discutée ci-dessus et renvoie un objet Range. L’objet Range fournit également une méthode merge qui fusionne la plage spécifiée dans l’objet Range.

Direction du texte

Il est possible de définir l’ordre de lecture du texte dans les cellules. L’ordre de lecture est l’ordre visuel dans lequel les caractères, les mots, etc. sont affichés. Par exemple, l’anglais est une langue de gauche à droite tandis que l’arabe est une langue de droite à gauche.

L’ordre de lecture est défini avec la propriété text_direction de l’objet Style. Aspose.Cells pour Python via .NET fournit des types de direction de texte prédéfinis dans l’énumération TextDirectionType.

Types de direction du texte Description
CONTEXTE L’ordre de lecture conforme à la langue du premier caractère entré
GAUCHE_DROITE Ordre de lecture de gauche à droite
DROITE_GAUCHE Ordre de lecture de droite à gauche
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")

Sujets avancés