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.GetStyle, spécifier les attributs de style et appliquer le formatage à l’aide de la méthode Cell.SetStyle. Un exemple est donné ci-dessous pour illustrer cette approche d’application de divers formatages sur une cellule.
// 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 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("Hello Aspose!"); | |
// Defining a Style object | |
Aspose.Cells.Style style; | |
// Get the style from A1 cell | |
style = cell.GetStyle(); | |
// Setting the vertical alignment | |
style.VerticalAlignment = TextAlignmentType.Center; | |
// Setting the horizontal alignment | |
style.HorizontalAlignment = 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.ShrinkToFit = true; | |
// Setting the bottom border color to red | |
style.Borders[BorderType.BottomBorder].Color = Color.Red; | |
// Setting the bottom border type to medium | |
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium; | |
// Applying the style to A1 cell | |
cell.SetStyle(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 :
- Ajouter un objet Style en appelant la méthode CreateStyle de la classe Workbook
- Accéder au nouvel objet Style ajouté
- Définir les propriétés/attributs souhaités de l’objet Style pour appliquer les paramètres de formatage souhaités
- 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.
// 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(); | |
// Adding a new worksheet to the Excel object | |
int i = workbook.Worksheets.Add(); | |
// Obtaining the reference of the first worksheet by passing its sheet index | |
Worksheet worksheet = workbook.Worksheets[i]; | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = worksheet.Cells["A1"]; | |
// Adding some value to the "A1" cell | |
cell.PutValue("Hello Aspose!"); | |
// Adding a new Style | |
Style style = workbook.CreateStyle(); | |
// Setting the vertical alignment of the text in the "A1" cell | |
style.VerticalAlignment = TextAlignmentType.Center; | |
// Setting the horizontal alignment of the text in the "A1" cell | |
style.HorizontalAlignment = 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.ShrinkToFit = true; | |
// Setting the bottom border color of the cell to red | |
style.Borders[BorderType.BottomBorder].Color = Color.Red; | |
// Setting the bottom border type of the cell to medium | |
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium; | |
// Assigning the Style object to the "A1" cell | |
cell.SetStyle(style); | |
// Apply the same style to some other cells | |
worksheet.Cells["B1"].SetStyle(style); | |
worksheet.Cells["C1"].SetStyle(style); | |
worksheet.Cells["D1"].SetStyle(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. Un exemple est donné ci-dessous pour illustrer cette approche d’application d’un style prédéfini sur une cellule.
// 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); | |
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook(); | |
// Create a style object . | |
Style style = workbook.CreateStyle(); | |
// Input a value to A1 cell. | |
workbook.Worksheets[0].Cells["A1"].PutValue("Test"); | |
// Apply the style to the cell. | |
workbook.Worksheets[0].Cells["A1"].SetStyle(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 prend également en charge cette fonctionnalité. Ce sujet explique comment nous utilisons cette fonctionnalité de manière efficace.
Comment formater des caractères sélectionnés
Aspose.Cells 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 de calcul est représentée par la classe Worksheet. La classe Worksheet fournit une collection Cells. Chaque élément dans 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.
// 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 first(default) worksheet by passing its sheet index | |
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("Visit Aspose!"); | |
// Setting the font of selected characters to bold | |
cell.Characters(6, 7).Font.IsBold = 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 offre une solution simple et rapide qui est discutée en détail dans cet article.
Mise en forme des lignes & colonnes
Aspose.Cells fournit une classe, Workbook qui représentent un fichier Microsoft Excel. La classe Workbook contient une collection Worksheets qui permet 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 fournit 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 ApplyStyle 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.
- Ajouter un objet Style à la classe Workbook en appelant sa méthode CreateStyle.
- Définir les propriétés de l’objet Style pour appliquer les paramètres de formatage.
- Activer les attributs pertinents pour l’objet StyleFlag.
- Affecter l’objet Style configuré à l’objet Row.
// 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 first (default) worksheet by passing its sheet index | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Adding a new Style to the styles | |
Style style = workbook.CreateStyle(); | |
// Setting the vertical alignment of the text in the "A1" cell | |
style.VerticalAlignment = TextAlignmentType.Center; | |
// Setting the horizontal alignment of the text in the "A1" cell | |
style.HorizontalAlignment = 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.ShrinkToFit = true; | |
// Setting the bottom border color of the cell to red | |
style.Borders[BorderType.BottomBorder].Color = Color.Red; | |
// Setting the bottom border type of the cell to medium | |
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium; | |
// Creating StyleFlag | |
StyleFlag styleFlag = new StyleFlag(); | |
styleFlag.HorizontalAlignment = true; | |
styleFlag.VerticalAlignment = true; | |
styleFlag.ShrinkToFit = true; | |
styleFlag.Borders = true; | |
styleFlag.FontColor = true; | |
// Accessing a row from the Rows collection | |
Row row = worksheet.Cells.Rows[0]; | |
// Assigning the Style object to the Style property of the row | |
row.ApplyStyle(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 ApplyStyle pour formater une colonne.
// 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 first (default) worksheet by passing its sheet index | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Adding a new Style to the styles | |
Style style = workbook.CreateStyle(); | |
// Setting the vertical alignment of the text in the "A1" cell | |
style.VerticalAlignment = TextAlignmentType.Center; | |
// Setting the horizontal alignment of the text in the "A1" cell | |
style.HorizontalAlignment = 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.ShrinkToFit = true; | |
// Setting the bottom border color of the cell to red | |
style.Borders[BorderType.BottomBorder].Color = Color.Red; | |
// Setting the bottom border type of the cell to medium | |
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium; | |
// Creating StyleFlag | |
StyleFlag styleFlag = new StyleFlag(); | |
styleFlag.HorizontalAlignment = true; | |
styleFlag.VerticalAlignment = true; | |
styleFlag.ShrinkToFit = true; | |
styleFlag.Borders = true; | |
styleFlag.FontColor = true; | |
// Accessing a column from the Columns collection | |
Column column = worksheet.Cells.Columns[0]; | |
// Applying the style to the column | |
column.ApplyStyle(style, styleFlag); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls"); |
Sujets avancés
- Paramètres d’alignement
- Paramètres de bordure
- Définir les formats conditionnels des fichiers Excel et ODS.
- Thèmes et couleurs d’Excel
- Paramètres de remplissage
- Paramètres de police
- Formater les cellules de feuille de calcul dans un classeur
- Mise en œuvre du système de date 1904
- Fusionner et scinder des cellules
- Paramètres de nombre
- Obtenir et définir le style des cellules