Formater les cellules

Introduction

Formater Cells à l’aide des méthodes GetStyle et SetStyle

Appliquez différents types de styles de mise en forme sur les cellules pour définir les couleurs d’arrière-plan ou de premier plan, les bordures, les polices, les alignements horizontaux et verticaux, le niveau d’indentation, la direction du texte, l’angle de rotation et bien plus encore.

Utilisation des méthodes GetStyle et SetStyle

Si les développeurs doivent appliquer différents styles de mise en forme à différentes cellules, il est préférable d’obtenir leStyle de la cellule à l’aideCell.GetStyle méthode, spécifiez les attributs de style, puis appliquez la mise en forme à l’aideCell.SetStyleméthode. Un exemple est donné ci-dessous pour démontrer cette approche pour appliquer 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");

Utilisation d’un objet de style pour formater différents Cells

Si les développeurs doivent appliquer le même style de mise en forme à différentes cellules, ils peuvent utiliserStyle objet. Veuillez suivre les étapes ci-dessous pour utiliser leStyleobjet:

  1. Ajouter unStyle objet en appelant leCréerStyle méthode de laCahierclasse
  2. Accéder au nouveauStyleobjet
  3. Définissez les propriétés/attributs souhaités duStyleobjet pour appliquer les paramètres de formatage souhaités
  4. Attribuez la configurationStyleobjectez à vos cellules désirées

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

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

Utilisation des styles prédéfinis Microsoft Excel 2007

Si vous devez appliquer différents styles de mise en forme pour Microsoft Excel 2007, appliquez les styles à l’aide de Aspose.Cells API. Un exemple est donné ci-dessous pour illustrer cette approche pour appliquer 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");

Formatage des caractères sélectionnés dans un Cell

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

Aspose.Cells prend également en charge cette fonctionnalité. Cette rubrique explique comment utiliser efficacement cette fonctionnalité.

Formatage des caractères sélectionnés

Aspose.Cells fournit une classe,Cahier qui représente un fichier Excel Microsoft. LeCahier classe contient leFeuilles de travail collection qui permet d’accéder à chaque feuille de calcul dans un fichier Excel. Une feuille de calcul est représentée par leFeuille de travail classe. LeFeuille de travail la classe offre uneCells le recueil. Chaque élément de laCells collection représente un objet de laCellclasse.

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

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

LePersonnages La méthode renvoie une instance deFontSettingclasse qui permet aux développeurs de formater les caractères de la même manière qu’ils le feraient pour 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 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");

Formatage des lignes et des colonnes

Parfois, les développeurs doivent appliquer le même formatage sur des lignes ou des colonnes. Appliquer une mise en forme sur les cellules une par une prend souvent plus de temps et n’est pas une bonne solution. Pour résoudre ce problème, Aspose.Cells fournit un moyen simple et rapide décrit en détail dans cet article.

Formatage des lignes et des colonnes

Aspose.Cells fournit une classe, laCahier qui représente un fichier Excel Microsoft. LeCahier classe contient unFeuilles de travail collection qui permet d’accéder à chaque feuille de calcul dans le fichier Excel. Une feuille de calcul est représentée par leFeuille de travail classe. LeFeuille de travail la classe offre uneCells le recueil. LeCellscollecte offre uneLignesle recueil.

Formater une ligne

Chaque élément de laLignes la collection représente unLigne objet. LeLignel’objet offre leAppliquerStyle méthode utilisée pour définir le formatage de la ligne. Pour appliquer le même formatage à une ligne, utilisez laStyleobjet. Les étapes ci-dessous montrent comment l’utiliser.

  1. Ajouter unStyle s’opposer à laCahier classe en appelant saCréerStyleméthode.
  2. Met leStylepropriétés de l’objet pour appliquer les paramètres de formatage.
  3. Activez les attributs pertinents pour leStyleDrapeauobjet.
  4. Attribuez la configurationStyle s’opposer à laLigneobjet.
// 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");

Formater une colonne

LeCells collection offre également uneColonnes le recueil. Chaque élément de laColonnes la collection représente unColonne objet. Semblable à unLigne objet, leColonne objet offre également laAppliquerStyleméthode de formatage d’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