Formater les cellules

Introduction

Comment formater les cellules en utilisant les méthodes GetStyle et SetStyle

Appliquer différents types de styles de formatage sur les cellules pour définir des couleurs de fond ou de premier plan, des bordures, des polices, des alignements horizontaux et verticaux, le niveau d’indentation, la direction du texte, l’angle de rotation et bien plus encore.

Comment utiliser les méthodes GetStyle et SetStyle

Si les développeurs ont besoin d’appliquer différents styles de formatage à différentes cellules, il est préférable d’obtenir le Style de la cellule en utilisant la méthode Cell.get_style, spécifier les attributs de style et appliquer le formatage à l’aide de la méthode Cell.set_style. Un exemple est donné ci-dessous pour illustrer cette approche d’application de divers formatages sur une cellule.

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")

Comment utiliser l’objet de style pour formater différentes cellules

Si les développeurs ont besoin d’appliquer le même style de formatage à différentes cellules, ils peuvent utiliser l’objet Style. Veuillez suivre les étapes ci-dessous pour utiliser l’objet Style :

  1. Ajouter un objet Style en appelant la méthode create_style de la classe Workbook
  2. Accéder au nouvel objet Style ajouté
  3. Définir les propriétés/attributs souhaités de l’objet Style pour appliquer les paramètres de formatage souhaités
  4. Attribuer l’objet Style configuré à vos cellules souhaitées

Cette approche peut grandement améliorer l’efficacité de vos applications et économiser de la mémoire également.

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")

Comment utiliser les styles prédéfinis de Microsoft Excel 2007

Si vous avez besoin d’appliquer différents styles de formatage pour Microsoft Excel 2007, appliquez les styles en utilisant l’API Aspose.Cells pour Python via .NET. Un exemple est donné ci-dessous pour démontrer cette approche d’application d’un style prédéfini sur une cellule.

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")

Comment formater des caractères sélectionnés dans une cellule

La gestion des paramètres de police explique comment formater du texte dans les cellules, mais cela explique seulement comment formater tout le contenu de la cellule. Et si vous voulez formater uniquement des caractères sélectionnés ?

Aspose.Cells pour Python via .NET supporte également cette fonctionnalité. Ce sujet explique comment utiliser cette fonctionnalité efficacement.

Comment formater des caractères sélectionnés

Aspose.Cells pour Python via .NET fournit une classe, Workbook qui représente un fichier Microsoft Excel. La classe Workbook contient la collection worksheets qui permet d’accéder à chaque feuille de calcul dans un 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.

La classe Cell fournit la méthode characters qui prend les paramètres suivants pour sélectionner une plage de caractères à l’intérieur d’une cellule :

  • Index de début, l’index du caractère à partir duquel la sélection commence.
  • Nombre de caractères, le nombre de caractères à sélectionner.

La méthode characters retourne une instance de la classe FontSetting qui permet aux développeurs de formater les caractères de la même manière qu’une cellule comme indiqué ci-dessous dans l’exemple de code. Dans le fichier de sortie, dans la cellule A1, le mot ‘Visite’ sera formaté avec la police par défaut mais ‘Aspose!’ est en gras et bleu.

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")

Comment formater les lignes et les colonnes

Parfois, les développeurs doivent appliquer le même formatage sur des lignes ou des colonnes. Appliquer le formatage sur chaque cellule prend souvent plus de temps et n’est pas une bonne solution. Pour résoudre ce problème, Aspose.Cells pour Python via .NET offre une méthode simple et rapide, décrite en détail dans cet article.

Mise en forme des lignes & colonnes

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

Comment formater une ligne

Chaque élément dans la collection rows représente un objet Row. L’objet Row offre la méthode apply_style utilisée pour définir le format de la ligne. Pour appliquer le même formatage à une ligne, utilisez l’objet Style. Les étapes ci-dessous montrent comment l’utiliser.

  1. Ajouter un objet Style à la classe Workbook en appelant sa méthode create_style.
  2. Définir les propriétés de l’objet Style pour appliquer les paramètres de formatage.
  3. Activer les attributs pertinents pour l’objet StyleFlag.
  4. Affecter l’objet Style configuré à l’objet 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")

Comment formater une colonne

La collection cells fournit également une collection columns. Chaque élément dans la collection columns représente un objet Column. Tout comme un objet Row, l’objet Column offre également la méthode apply_style pour formater une colonne.

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")

Sujets avancés