Formattazione dei dati
Approcci per Formattare i Dati nelle Celle
È un fatto comune che se le celle del foglio di lavoro sono formattate correttamente, diventa più facile per gli utenti leggere i contenuti (dati) della cella. Ci sono molti modi per formattare le celle e i loro contenuti. Il modo più semplice è quello di formattare le celle utilizzando Microsoft Excel in un ambiente WYSIWYG durante la creazione di un Foglio di Calcolo del Designer. Dopo aver creato il foglio di calcolo del designer, è possibile aprire il foglio di calcolo utilizzando Aspose.Cells mantenendo tutte le impostazioni di formato salvate con il foglio di calcolo. Un altro modo per formattare le celle e i loro contenuti è utilizzare l’API Aspose.Cells. In questo argomento, descriveremo due approcci per formattare le celle e i loro contenuti con l’uso dell’API Aspose.Cells.
Formattazione celle
I programmatori possono formattare le celle e i loro contenuti utilizzando l’API flessibile di Aspose.Cells. Aspose.Cells fornisce una classe, Workbook, che rappresenta un file Microsoft Excel. La classe Workbook contiene una WorksheetCollection che consente di accedere a ciascun foglio di lavoro in un file Excel. Un foglio di lavoro è rappresentato dalla classe Worksheet. La classe Worksheet fornisce una raccolta di celle. Ciascun elemento nella raccolta di Cells rappresenta un oggetto della classe Cell.
Aspose.Cells fornisce la proprietà Style nella classe Cell, utilizzata per impostare lo stile di formattazione di una cella. Inoltre, Aspose.Cells fornisce anche una classe Style che viene utilizzata per lo stesso scopo. Applicare diversi tipi di stili di formattazione alle celle per impostare i loro colori di sfondo o primo piano, i bordi, i caratteri, l’allineamento orizzontale e verticale, il livello di rientro, la direzione del testo, l’angolo di rotazione e molto altro.
Utilizzo del metodo setStyle
Quando si applicano stili di formattazione diversi a celle diverse, è meglio utilizzare il metodo setStyle della classe Cell. Di seguito è riportato un esempio per dimostrare l’uso del metodo setStyle per applicare varie impostazioni di formattazione su una cella.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(FormattingCellsUsingsetStyleMethod.class); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
Cells cells = worksheet.getCells(); | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = cells.get("A1"); | |
// Adding some value to the "A1" cell | |
cell.setValue("Hello Aspose!"); | |
Style style = cell.getStyle(); | |
// Setting the vertical alignment of the text in the "A1" cell | |
style.setVerticalAlignment(TextAlignmentType.CENTER); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
style.setHorizontalAlignment(TextAlignmentType.CENTER); | |
// Setting the font color of the text in the "A1" cell | |
Font font = style.getFont(); | |
font.setColor(Color.getGreen()); | |
// Setting the cell to shrink according to the text contained in it | |
style.setShrinkToFit(true); | |
// Setting the bottom border | |
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.MEDIUM, Color.getRed()); | |
// Saved style | |
cell.setStyle(style); | |
// Saving the modified Excel file in default (that is Excel 2003) format | |
workbook.save(dataDir + "output.xls"); |
Utilizzo dell’oggetto Style
Quando si applica lo stesso stile di formattazione a celle diverse, utilizzare l’oggetto Style.
- Aggiungere un oggetto Style alla raccolta Styles della classe Workbook chiamando il metodo createStyle della classe Workbook.
- Accedi al nuovo oggetto Style aggiunto dalla collezione Styles.
- Imposta le proprietà desiderate dell’oggetto Style per applicare le impostazioni di formattazione desiderate.
- Assegna l’oggetto Style configurato alla proprietà Style di qualsiasi cella desiderata.
Questo approccio può migliorare notevolmente l’efficienza delle tue applicazioni e risparmiare memoria anche.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(FormattingCellsUsingStyleObject.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
// Accessing the first worksheet in the Excel file | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
Cells cells = worksheet.getCells(); | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = cells.get("A1"); | |
// Adding some value to the "A1" cell | |
cell.setValue("Hello Aspose!"); | |
// Adding a new Style to the styles collection of the Excel object | |
Style style = workbook.createStyle(); | |
// Setting the vertical alignment of the text in the "A1" cell | |
style.setVerticalAlignment(TextAlignmentType.CENTER); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
style.setHorizontalAlignment(TextAlignmentType.CENTER); | |
// Setting the font color of the text in the "A1" cell | |
Font font = style.getFont(); | |
font.setColor(Color.getGreen()); | |
// Setting the cell to shrink according to the text contained in it | |
style.setShrinkToFit(true); | |
// Setting the bottom border | |
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.MEDIUM, Color.getRed()); | |
// Saved style | |
cell.setStyle(style); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "FCUsingStyleObject_out.xls"); |
Applicazione degli effetti di riempimento a sfumatura
Per applicare i tuoi desiderati effetti di riempimento gradiente alla cella, utilizza il metodo setTwoColorGradient dell’oggetto Style di conseguenza.
Esempio di codice
L’output seguente è ottenuto eseguendo il codice sottostante.
Applicazione degli effetti di riempimento gradiente
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(ApplyGradientFillEffects.class) + "data/"; | |
// Instantiate a new Workbook | |
Workbook workbook = new Workbook(); | |
// Get the first worksheet (default) in the workbook | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Input a value into B3 cell | |
worksheet.getCells().get(2, 1).putValue("test"); | |
// Get the Style of the cell | |
Style style = worksheet.getCells().get("B3").getStyle(); | |
// Set Gradient pattern on | |
style.setGradient(true); | |
// Specify two color gradient fill effects | |
style.setTwoColorGradient(Color.fromArgb(255, 255, 255), Color.fromArgb(79, 129, 189), | |
GradientStyleType.HORIZONTAL, 1); | |
// Set the color of the text in the cell | |
style.getFont().setColor(Color.getRed()); | |
// Specify horizontal and vertical alignment settings | |
style.setHorizontalAlignment(TextAlignmentType.CENTER); | |
style.setVerticalAlignment(TextAlignmentType.CENTER); | |
// Apply the style to the cell | |
worksheet.getCells().get("B3").setStyle(style); | |
// Set the third row height in pixels | |
worksheet.getCells().setRowHeightPixel(2, 53); | |
// Merge the range of cells (B3:C3) | |
worksheet.getCells().merge(2, 1, 1, 2); | |
// Save the Excel file | |
workbook.save(dataDir + "ApplyGradientFillEffects_out.xlsx"); |
Configurazione delle impostazioni di allineamento
Chiunque abbia usato Microsoft Excel per formattare le celle sarà familiare con le impostazioni di allineamento in Microsoft Excel.
Impostazioni di allineamento in Microsoft Excel
Come si può vedere dalla figura sopra, ci sono diversi tipi di opzioni di allineamento:
- Allineamento del testo (orizzontale e verticale)
- Rientro.
- Orientamento.
- Controllo testo.
- Direzione del testo.
Tutte queste impostazioni di allineamento sono completamente supportate da Aspose.Cells e sono discusse in modo più dettagliato di seguito.
Configurazione delle impostazioni di allineamento
Aspose.Cells fornisce una classe, Workbook, che rappresenta un file Excel. La classe Workbook contiene una WorksheetCollection che consente l’accesso a ciascun foglio di lavoro nel file Excel. Un foglio di lavoro è rappresentato dalla classe Worksheet.
La classe Worksheet fornisce una raccolta di celle. Ogni elemento nella raccolta di celle rappresenta un oggetto della classe Cell.
Aspose.Cells fornisce il metodo setStyle nella classe Cell che viene utilizzato per formattare la cella. La classe Style fornisce utili proprietà per configurare le impostazioni del font.
Seleziona qualsiasi tipo di allineamento del testo utilizzando l’enumerazione TextAlignmentType. I tipi di allineamento del testo predefiniti nell’enumerazione TextAlignmentType sono:
Tipi di Allineamento del Testo | Descrizione |
---|---|
Bottom | Rappresenta l’allineamento del testo in basso |
Center | Rappresenta l’allineamento del testo al centro |
CenterAcross | Rappresenta l’allineamento del testo al centro tra le celle |
Distributed | Rappresenta l’allineamento distribuito del testo |
Fill | Rappresenta l’allineamento di riempimento del testo |
General | Rappresenta l’allineamento del testo generale |
Justify | Rappresenta l’allineamento del testo giustificato |
Left | Rappresenta l’allineamento del testo a sinistra |
Right | Rappresenta l’allineamento del testo a destra |
Top | Rappresenta l’allineamento del testo in alto |
È anche possibile applicare l’impostazione giustifica distribuita utilizzando il metodo Style.setJustifyDistributed().
|
Allineamento Orizzontale
Utilizza il metodo setHorizontalAlignment dell’oggetto Style per allineare il testo orizzontalmente.
Il seguente output è ottenuto eseguendo il codice di esempio qui sotto:
Allineamento del testo orizzontalmente
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(TextAlignmentHorizontal.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Setting the horizontal alignment of the text in the "A1" cell | |
style.setHorizontalAlignment(TextAlignmentType.CENTER); | |
// Saved style | |
cell.setStyle(style); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "TAHorizontal_out.xls"); |
Allineamento Verticale
Utilizza il metodo setVerticalAlignment dell’oggetto Style per allineare il testo verticalmente.
Il risultato seguente viene ottenuto quando VerticalAlignment è impostato su centro.
Allineamento del testo verticalmente
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(TextAlignmentVertical.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Setting the vertical alignment of the text in a cell | |
Style style1 = cell.getStyle(); | |
style1.setVerticalAlignment(TextAlignmentType.CENTER); | |
cell.setStyle(style1); | |
// Saved style | |
cell.setStyle(style1); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "TAVertical_out.xls"); |
Rientro
È possibile impostare il livello di rientro del testo in una cella utilizzando il metodo setIndentLevel dell’oggetto Style.
Il risultato seguente viene ottenuto quando IndentLevel è impostato su 2.
Livello di rientro regolato su 2
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(Indentation.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Setting the vertical alignment of the text in a cell | |
Style style1 = cell.getStyle(); | |
style1.setIndentLevel(2); | |
cell.setStyle(style1); | |
// Saved style | |
cell.setStyle(style1); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "Indentation_out.xls"); |
Orientamento
Imposta l’orientamento (rotazione) del testo in una cella con il metodo setRotationAngle dell’oggetto Style.
Il risultato seguente viene ottenuto quando l’angolo di rotazione è impostato su 25.
Angolo di rotazione impostato su 25
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(Orientation.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Setting the rotation of the text (inside the cell) to 25 | |
Style style1 = cell.getStyle(); | |
style1.setRotationAngle(25); | |
cell.setStyle(style1); | |
// Saved style | |
cell.setStyle(style1); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "Orientation_out.xls"); |
Controllo del Testo
La seguente sezione discute come controllare il testo impostando il rientro del testo, adattamento alla cella e altre opzioni di formattazione.
Testo a Capo
Il word wrap del testo in una cella rende più facile la lettura: l’altezza della cella si adatta a tutto il testo, anziché tagliarlo o farlo traboccare nelle celle adiacenti.
Attiva o disattiva il word wrap con il metodo setTextWrapped dell’oggetto Style.
Il risultato seguente viene ottenuto quando il word wrap è abilitato.
Testo avvolto all’interno della cella
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(WrapText.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Enabling the text to be wrapped within the cell | |
Style style1 = cell.getStyle(); | |
style1.setTextWrapped(true); | |
cell.setStyle(style1); | |
// Saved style | |
cell.setStyle(style1); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "WrapText_out.xls"); |
Ridimensionamento per adattarsi
Un’opzione per il word wrap in un campo è ridurre la dimensione del testo per adattarlo alle dimensioni di una cella. Questo avviene impostando la proprietà IsTextWrapped dell’oggetto Style su true.
Il seguente output è ottenuto quando il testo viene ridotto per adattarsi alla cella.
Testo ridotto per adattarsi all’interno dei limiti della cella
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(ShrinkingToFit.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Shrinking the text to fit according to the dimensions of the cell | |
Style style1 = cell.getStyle(); | |
style1.setShrinkToFit(true); | |
cell.setStyle(style1); | |
// Saved style | |
cell.setStyle(style1); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "ShrinkingToFit_out.xls"); |
Unione di celle
Come Microsoft Excel, Aspose.Cells supporta l’unione di più celle in una sola.
Il seguente output è ottenuto se le tre celle nella prima riga vengono unite per creare una grande cella singola.
Tre celle unite per creare una grande cella
Usa il metodo di unione della collezione Cells per unire le celle. Il metodo di unione prende i seguenti parametri:
- Prima riga, la prima riga da cui iniziare a unire.
- Prima colonna, la prima colonna da cui iniziare a unire.
- Numero di righe, il numero di righe da unire.
- Numero di colonne, il numero di colonne da unire.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(MergingCellsInWorksheet.class) + "data/"; | |
// Create a Workbook. | |
Workbook wbk = new Workbook(); | |
// Create a Worksheet and get the first sheet. | |
Worksheet worksheet = wbk.getWorksheets().get(0); | |
// Create a Cells object to fetch all the cells. | |
Cells cells = worksheet.getCells(); | |
// Merge some Cells (C6:E7) into a single C6 Cell. | |
cells.merge(5, 2, 2, 3); | |
// Input data into C6 Cell. | |
worksheet.getCells().get(5, 2).setValue("This is my value"); | |
// Create a Style object to fetch the Style of C6 Cell. | |
Style style = worksheet.getCells().get(5, 2).getStyle(); | |
// Create a Font object | |
Font font = style.getFont(); | |
// Set the name. | |
font.setName("Times New Roman"); | |
// Set the font size. | |
font.setSize(18); | |
// Set the font color | |
font.setColor(Color.getBlue()); | |
// Bold the text | |
font.setBold(true); | |
// Make it italic | |
font.setItalic(true); | |
// Set the backgrond color of C6 Cell to Red | |
style.setForegroundColor(Color.getRed()); | |
style.setPattern(BackgroundType.SOLID); | |
// Apply the Style to C6 Cell. | |
cells.get(5, 2).setStyle(style); | |
// Save the Workbook. | |
wbk.save(dataDir + "mergingcells_out.xls"); | |
wbk.save(dataDir + "mergingcells_out.xlsx"); | |
wbk.save(dataDir + "mergingcells_out.ods"); | |
// Print message | |
System.out.println("Process completed successfully"); |
Direzione del testo
È possibile impostare l’ordine di lettura del testo nelle celle. L’ordine di lettura è l’ordine visivo in cui caratteri, parole, ecc. vengono visualizzati. Ad esempio, l’inglese è una lingua da sinistra a destra, mentre l’arabo è una lingua da destra a sinistra.
L’ordine di lettura viene impostato con la proprietà TextDirection dell’oggetto Style. Aspose.Cells fornisce tipi di direzione del testo predefiniti nell’enumerazione TextDirectionType.
Tipi di direzione del testo | Descrizione |
---|---|
Context | L’ordine di lettura coerente con la lingua del primo carattere inserito |
LeftToRight | Ordine di lettura da sinistra a destra |
RightToLeft | Ordine di lettura da destra a sinistra |
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(ChangeTextDirection.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding the current system date to "A1" cell | |
Cell cell = cells.get("A1"); | |
Style style = cell.getStyle(); | |
// Adding some value to the "A1" cell | |
cell.setValue("Visit Aspose!"); | |
// Setting the text direction from right to left | |
Style style1 = cell.getStyle(); | |
style1.setTextDirection(TextDirectionType.RIGHT_TO_LEFT); | |
cell.setStyle(style1); | |
// Saved style | |
cell.setStyle(style1); | |
// Saving the modified Excel file in default format | |
workbook.save(dataDir + "ChangeTextDirection_out.xls"); |
Il seguente output è ottenuto se l’ordine di lettura del testo è impostato da destra a sinistra.
Impostazione dell’ordine di lettura del testo da destra a sinistra
Formattazione dei caratteri selezionati in una cella
Gestione delle impostazioni del carattere spiega come formattare le celle ma solo come formattare il contenuto delle intere celle. E se si vuole formattare solo alcuni caratteri selezionati?
Aspose.Cells supporta questa funzione. Questo argomento spiega come utilizzare questa funzione.
Formattazione dei caratteri selezionati
Aspose.Cells fornisce una classe, Workbook, che rappresenta un file Microsoft Excel. La classe Workbook contiene una raccolta di Fogli di lavoro che consente di accedere a ciascun foglio di lavoro nel file Excel. Un foglio di lavoro è rappresentato dalla classe Worksheet. La classe Worksheet fornisce una raccolta di celle. Ogni elemento nella raccolta di celle rappresenta un oggetto della classe Cell.
La classe Cell fornisce un metodo caratteri che accetta i seguenti parametri per selezionare un intervallo di caratteri in una cella:
- Indice di inizio, l’indice del carattere da cui iniziare la selezione.
- Numero di caratteri, il numero di caratteri da selezionare.
Nel file di output, nella cella A1, la parola ‘Visita’ è formattata con il carattere predefinito ma ‘Aspose!’ è in grassetto e blu.
Formattazione dei caratteri selezionati
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// Path to source file | |
String dataDir = Utils.getSharedDataDir(FormattingSelectedCharacters.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
Cells cells = worksheet.getCells(); | |
// Adding some value to the "A1" cell | |
Cell cell = cells.get("A1"); | |
cell.setValue("Visit Aspose!"); | |
Font font = cell.characters(6, 7).getFont(); | |
// Setting the font of selected characters to bold | |
font.setBold(true); | |
// Setting the font color of selected characters to blue | |
font.setColor(Color.getBlue()); | |
// Saving the Excel file | |
workbook.save(dataDir + "FSCharacters_out.xls"); |
Attivazione dei Fogli e Creazione di una Cella Attiva o Selezione di un Intervallo di Celle nel Foglio di lavoro
A volte potresti aver bisogno di attivare un foglio di lavoro specifico in modo che sia il primo visualizzato quando qualcuno apre il file in Microsoft Excel. Potresti anche aver bisogno di attivare una cella specifica in modo che le barre di scorrimento si spostino sulla cella attiva in modo che sia chiaramente visibile. Aspose.Cells è in grado di fare tutti i compiti sopra menzionati.
Un foglio attivo è il foglio su cui stai lavorando in un workbook. Il nome sulla scheda del foglio attivo è in grassetto per impostazione predefinita. Una cella attiva, invece, è la cella selezionata e in cui vengono inseriti i dati quando si inizia a digitare. Solo una cella è attiva alla volta. La cella attiva è circondata da un bordo spesso per renderla visibile rispetto alle altre celle. Aspose.Cells ti consente anche di selezionare un intervallo di celle nel foglio di lavoro.
Attivare un Foglio e Rendere una Cella Attiva
Aspose.Cells fornisce un’API specifica per queste attività. Ad esempio, il metodo WorksheetCollection.setActiveSheetIndex è utile per impostare un foglio attivo. Allo stesso modo, il metodo Worksheet.setActiveCell viene utilizzato per impostare e recuperare una cella attiva in un foglio di lavoro.
Se desideri che le barre di scorrimento orizzontale e verticale si spostino sulla posizione dell’indice di riga e colonna per dare una buona visualizzazione dei dati selezionati quando il file viene aperto in Microsoft Excel, utilizza le proprietà Worksheet.setFirstVisibleRow e Worksheet.setFirstVisibleColumn.
Nell’esempio seguente è mostrato come attivare un foglio di lavoro e fare in modo che una cella in esso sia attiva. Le barre di scorrimento sono spostate per fare in modo che la 2a riga e la 2a colonna siano la loro prima riga e colonna visibile.
Impostare la cella B2 come una cella attiva
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(MakeCellActive.class) + "data/"; | |
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook(); | |
// Get the first worksheet in the workbook. | |
Worksheet worksheet1 = workbook.getWorksheets().get(0); | |
// Get the cells in the worksheet. | |
Cells cells = worksheet1.getCells(); | |
// Input data into B2 cell. | |
cells.get(1, 1).setValue("Hello World!"); | |
// Set the first sheet as an active sheet. | |
workbook.getWorksheets().setActiveSheetIndex(0); | |
// Set B2 cell as an active cell in the worksheet. | |
worksheet1.setActiveCell("B2"); | |
// Set the B column as the first visible column in the worksheet. | |
worksheet1.setFirstVisibleColumn(1); | |
// Set the 2nd row as the first visible row in the worksheet. | |
worksheet1.setFirstVisibleRow(1); | |
// Save the Excel file. | |
workbook.save(dataDir + "MakeCellActive_out.xls"); |
Selezione di un Intervallo di Celle nel Foglio di lavoro
Aspose.Cells fornisce il metodo Worksheet.selectRange(int startRow, int startColumn, int totalRows, int totalColumns, bool removeOthers). Utilizzando l’ultimo parametro - removeOthers - su true, vengono rimossi altri selezioni di celle o intervalli di celle nel foglio.
L’esempio seguente mostra come selezionare un intervallo di celle nella scheda attiva.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(SelectRangeofCellsinWorksheet.class) + "data/"; | |
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook(); | |
// Get the first worksheet in the workbook. | |
Worksheet worksheet1 = workbook.getWorksheets().get(0); | |
// Get the cells in the worksheet. | |
Cells cells = worksheet1.getCells(); | |
// Input data into B2 cell. | |
cells.get(1, 1).setValue("Hello World!"); | |
// Set the first sheet as an active sheet. | |
workbook.getWorksheets().setActiveSheetIndex(0); | |
// Select range of cells(A1:E10) in the worksheet. | |
worksheet1.selectRange(0, 0, 10, 5, true); | |
// Save the Excel file. | |
workbook.save(dataDir + "SROfCInWorksheet_out.xlsx"); |
Formattazione righe e colonne
La formattazione delle righe e delle colonne in un foglio di calcolo per dare un aspetto al report è probabilmente la funzionalità più utilizzata dell’applicazione Excel. Le API di Aspose.Cells forniscono anche questa funzionalità attraverso il suo modello di dati esponendo la classe Style che gestisce principalmente tutte le funzionalità relative allo stile come il font e i suoi attributi, l’allineamento del testo, i colori di sfondo/primo piano, i bordi, il formato di visualizzazione per numeri e letterali delle date e così via. Un’altra utile classe fornita dalle API di Aspose.Cells è StyleFlag che consente il riuso dell’oggetto Style.
In questo articolo cercheremo di spiegare come utilizzare l’API Aspose.Cells for Java per applicare la formattazione alle righe e alle colonne.
Formattare Righe e Colonne
Aspose.Cells fornisce una classe, Workbook che rappresenta un file di Microsoft Excel. La classe Workbook contiene una WorksheetCollection che consente l’accesso a ciascuna scheda nel file Excel. Una scheda è rappresentata dalla classe Worksheet. La classe Worksheet fornisce la collezione Cells. La collezione Cells fornisce una collezione Rows.
Formattazione di una riga
Ogni elemento nella collezione Rows rappresenta un oggetto di tipo Row. L’oggetto Row offre il metodo applyStyle utilizzato per applicare la formattazione a una riga.
Per applicare la stessa formattazione a una riga, utilizzare l’oggetto Style:
- Aggiungere un oggetto Style alla classe Workbook chiamando il suo metodo createStyle.
- Impostare le proprietà dell’oggetto Style per applicare le impostazioni di formattazione.
- Assegnare l’oggetto Style configurato al metodo applyStyle di un oggetto Row.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(FormattingARow.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
Cells cells = worksheet.getCells(); | |
// Adding a new Style to the styles collection of the Excel object Accessing the newly added Style to the Excel object | |
Style style = workbook.createStyle(); | |
// Setting the vertical alignment of the text in the cell | |
style.setVerticalAlignment(TextAlignmentType.CENTER); | |
// Setting the horizontal alignment of the text in the cell | |
style.setHorizontalAlignment(TextAlignmentType.CENTER); | |
// Setting the font color of the text in the cell | |
Font font = style.getFont(); | |
font.setColor(Color.getGreen()); | |
// Shrinking the text to fit in the cell | |
style.setShrinkToFit(true); | |
// Setting the bottom border of the cell | |
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.MEDIUM, Color.getRed()); | |
// Creating StyleFlag | |
StyleFlag styleFlag = new StyleFlag(); | |
styleFlag.setHorizontalAlignment(true); | |
styleFlag.setVerticalAlignment(true); | |
styleFlag.setShrinkToFit(true); | |
styleFlag.setBottomBorder(true); | |
styleFlag.setFontColor(true); | |
// Accessing a row from the Rows collection | |
Row row = cells.getRows().get(0); | |
// Assigning the Style object to the Style property of the row | |
row.applyStyle(style, styleFlag); | |
// Saving the Excel file | |
workbook.save(dataDir + "FormattingARow_out.xls"); |
Formattazione di una colonna
La collezione Cells fornisce una collezione Columns. Ogni elemento nella collezione Columns rappresenta un oggetto di tipo Column. Similmente all’oggetto Row, l’oggetto Column offre il metodo applyStyle utilizzato per impostare la formattazione della colonna. Utilizzare il metodo applyStyle dell’oggetto Column per formattare una colonna allo stesso modo di una riga.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(FormattingAColumn.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Accessing the added worksheet in the Excel file | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
Cells cells = worksheet.getCells(); | |
// Adding a new Style to the styles collection of the Excel object Accessing the newly added Style to the Excel object | |
Style style = workbook.createStyle(); | |
// Setting the vertical alignment of the text in the cell | |
style.setVerticalAlignment(TextAlignmentType.CENTER); | |
// Setting the horizontal alignment of the text in the cell | |
style.setHorizontalAlignment(TextAlignmentType.CENTER); | |
// Setting the font color of the text in the cell | |
Font font = style.getFont(); | |
font.setColor(Color.getGreen()); | |
// Shrinking the text to fit in the cell | |
style.setShrinkToFit(true); | |
// Setting the bottom border of the cell | |
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.MEDIUM, Color.getRed()); | |
// Creating StyleFlag | |
StyleFlag styleFlag = new StyleFlag(); | |
styleFlag.setHorizontalAlignment(true); | |
styleFlag.setVerticalAlignment(true); | |
styleFlag.setShrinkToFit(true); | |
styleFlag.setBottomBorder(true); | |
styleFlag.setFontColor(true); | |
// Accessing a column from the Columns collection | |
Column column = cells.getColumns().get(0); | |
// Applying the style to the column | |
column.applyStyle(style, styleFlag); | |
// Saving the Excel file | |
workbook.save(dataDir + "FormattingAColumn_out.xls"); |
Impostazione del formato di visualizzazione dei numeri e delle date per righe e colonne
Se il requisito è impostare il formato di visualizzazione di numeri e date per un’intera riga o colonna, il processo è più o meno lo stesso come discusso sopra, tuttavia, anziché impostare i parametri per i contenuti testuali, si imposterà la formattazione per numeri e date utilizzando Style.Number o Style.Custom. Si noti che la proprietà Style.Number è di tipo intero e si riferisce ai formati numerici e di data incorporati, mentre la proprietà Style.Custom è di tipo stringa e accetta i pattern validi.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(SettingDisplayFormat.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the first (default) worksheet by passing its sheet index | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Adding a new Style to the styles collection of the Workbook object | |
Style style = workbook.createStyle(); | |
// Setting the Number property to 4 which corresponds to the pattern #,##0.00 | |
style.setNumber(4); | |
// Creating an object of StyleFlag | |
StyleFlag flag = new StyleFlag(); | |
// Setting NumberFormat property to true so that only this aspect takes effect from Style object | |
flag.setNumberFormat(true); | |
// Applying style to the first row of the worksheet | |
worksheet.getCells().getRows().get(0).applyStyle(style, flag); | |
// Re-initializing the Style object | |
style = workbook.createStyle(); | |
// Setting the Custom property to the pattern d-mmm-yy | |
style.setCustom("d-mmm-yy"); | |
// Applying style to the first column of the worksheet | |
worksheet.getCells().getColumns().get(0).applyStyle(style, flag); | |
// Saving spreadsheet on disc | |
workbook.save(dataDir + "SDisplayFormat_out.xlsx"); |