Formatta le celle

introduzione

Formattare Cells utilizzando i metodi GetStyle e SetStyle

Applica diversi tipi di stili di formattazione alle celle per impostare colori di sfondo o di primo piano, bordi, caratteri, allineamenti orizzontali e verticali, livello di rientro, direzione del testo, angolo di rotazione e molto altro.

Utilizzo dei metodi GetStyle e SetStyle

Se gli sviluppatori devono applicare diversi stili di formattazione a celle diverse, è meglio ottenere il formatoStile della cella utilizzandoCell.GetStyle metodo, specificare gli attributi di stile e quindi applicare la formattazione utilizzandoCell.SetStylemetodo. Di seguito viene fornito un esempio per dimostrare questo approccio per applicare varie formattazioni su una cella.

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

Utilizzo dell’oggetto stile per formattare diversamente Cells

Se gli sviluppatori devono applicare lo stesso stile di formattazione a celle diverse, possono utilizzareStile oggetto. Si prega di seguire i passaggi seguenti per utilizzare ilStileoggetto:

  1. Aggiungere unStile oggetto chiamando ilCrea stile metodo delCartella di lavoroclasse
  2. Accedi ai nuovi aggiuntiStileoggetto
  3. Impostare le proprietà/attributi desiderati del fileStileoggetto per applicare le impostazioni di formattazione desiderate
  4. Assegna il configuratoStileopporsi alle celle desiderate

Questo approccio può migliorare notevolmente l’efficienza delle tue applicazioni e risparmiare anche memoria.

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

Utilizzando Microsoft Excel 2007 Stili predefiniti

Se è necessario applicare stili di formattazione diversi per Microsoft Excel 2007, applicare gli stili utilizzando Aspose.Cells API. Di seguito viene fornito un esempio per dimostrare questo approccio per applicare uno stile predefinito su una cella.

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

Formattazione dei caratteri selezionati in un Cell

La gestione delle impostazioni dei caratteri spiega come formattare il testo nelle celle, ma spiega solo come formattare tutto il contenuto della cella. Cosa succede se si desidera formattare solo i caratteri selezionati?

Aspose.Cells supporta anche questa funzione. Questo argomento spiega come utilizzare questa funzione in modo efficace.

Formattazione dei caratteri selezionati

Aspose.Cells offre un corso,Cartella di lavoro che rappresenta un file Excel Microsoft. IlCartella di lavoro classe contiene ilFogli di lavoro raccolta che consente l’accesso a ciascun foglio di lavoro in un file Excel. Un foglio di lavoro è rappresentato daFoglio di lavoro classe. IlFoglio di lavoro la classe fornisce aCells collezione. Ogni elemento delCells collezione rappresenta un oggetto dellaCellclasse.

IlCell la classe fornisce ilCaratterimetodo che accetta i seguenti parametri per selezionare un intervallo di caratteri all’interno di una cella:

  • Inizio indice, l’indice del carattere da cui inizia la selezione.
  • Numero di caratteri, il numero di caratteri da selezionare.

IlCaratteri Il metodo restituisce un’istanza diImpostazione carattereclass che consente agli sviluppatori di formattare i caratteri nello stesso modo in cui farebbero con una cella, come mostrato di seguito nell’esempio di codice. Nel file di output, nella cella A1, la parola ‘Visit’ sarà formattata con il font predefinito ma ‘Aspose!’ è in grassetto e blu.

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

Formattazione di righe e colonne

A volte, gli sviluppatori devono applicare la stessa formattazione a righe o colonne. L’applicazione della formattazione alle celle una per una spesso richiede più tempo e non è una buona soluzione. Per risolvere questo problema, Aspose.Cells fornisce un modo semplice e veloce discusso in dettaglio in questo articolo.

Formattazione di righe e colonne

Aspose.Cells mette a disposizione un corso, ilCartella di lavoro che rappresenta un file Excel Microsoft. IlCartella di lavoro la classe contiene unFogli di lavoro raccolta che consente l’accesso a ciascun foglio di lavoro nel file Excel. Un foglio di lavoro è rappresentato daFoglio di lavoro classe. IlFoglio di lavoro la classe fornisce aCells collezione. IlCellsla raccolta fornisce aRighecollezione.

Formattazione di una riga

Ogni elemento delRighe collezione rappresenta aRiga oggetto. IlRigaoggetto offre ilApplica stile metodo utilizzato per impostare la formattazione della riga. Per applicare la stessa formattazione a una riga, utilizzare ilStileoggetto. I passaggi seguenti mostrano come usarlo.

  1. Aggiungere unStile opporsi alCartella di lavoro class chiamando itsCrea stilemetodo.
  2. Impostare ilStileproprietà dell’oggetto per applicare le impostazioni di formattazione.
  3. Attiva gli attributi rilevanti per il fileStyleFlagoggetto.
  4. Assegna il configuratoStile opporsi alRigaoggetto.
// 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");

Formattazione di una colonna

IlCells raccolta fornisce anche aColonne collezione. Ogni elemento delColonne collezione rappresenta aColonna oggetto. Simile all’aRiga oggetto, ilColonna oggetto offre anche ilApplica stilemetodo per la formattazione di una colonna.

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

Argomenti avanzati