Formateo de datos

Enfoques para formatear datos en Cells

Es un hecho común que si las celdas de la hoja de trabajo tienen el formato adecuado, a los usuarios les resultará más fácil leer el contenido (datos) de la celda. Hay muchas formas de formatear celdas y su contenido. La forma más sencilla es dar formato a las celdas utilizando Microsoft Excel en un entorno WYSIWYG al crear una hoja de cálculo de diseñador. Después de crear la hoja de cálculo del diseñador, puede abrir la hoja de cálculo usando Aspose.Cells manteniendo todas las configuraciones de formato guardadas con la hoja de cálculo. Otra forma de dar formato a las celdas y su contenido es usar Aspose.Cells API. En este tema, describiremos dos enfoques para dar formato a las celdas y su contenido con el uso de Aspose.Cells API.

Formateo Cells

Los desarrolladores pueden formatear celdas y su contenido utilizando el API flexible de Aspose.Cells. Aspose.Cells proporciona una clase,Libro de trabajo , que representa un archivo de Excel Microsoft. ÉlLibro de trabajo la clase contiene unColección de hojas de trabajo que permite el acceso a cada hoja de trabajo en un archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase. ÉlHoja de cálculo class proporciona una colección Cells. Cada artículo en elCellscolección representa un objeto deCell clase.

Aspose.Cells proporciona elEstilo propiedad en elCell class, que se utiliza para establecer el estilo de formato de una celda. Además, Aspose.Cells también proporciona unEstilo clase que se utiliza para servir al mismo propósito. Aplique diferentes tipos de estilos de formato en las celdas para establecer sus colores de fondo o de primer plano, bordes, fuentes, alineaciones horizontales y verticales, nivel de sangría, dirección del texto, ángulo de rotación y mucho más.

Usando el método setStyle

Al aplicar diferentes estilos de formato a diferentes celdas, es mejor usar el método setStyle delCell clase. A continuación se proporciona un ejemplo para demostrar el uso del método setStyle para aplicar varias configuraciones de formato en una celda.

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

Uso del objeto de estilo

Al aplicar el mismo estilo de formato a diferentes celdas, use elEstilo objeto.

  1. Agrega unEstilo objeto a la colección Styles de laLibro de trabajo clase llamando al método createStyle de la clase Workbook.
  2. Acceda al objeto Estilo recién agregado desde la colección Estilos.
  3. Establezca las propiedades deseadas del objeto Estilo para aplicar la configuración de formato deseada.
  4. Asigne el objeto Estilo configurado a la propiedad Estilo de cualquier celda deseada.

Este enfoque puede mejorar en gran medida la eficiencia de sus aplicaciones y también ahorrar memoria.

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

Aplicación de efectos de relleno degradado

Para aplicar los efectos de relleno de degradado deseados a la celda, utilice el método setTwoColorGradient del objeto Style según corresponda.

Ejemplo de código

El siguiente resultado se logra ejecutando el siguiente código.

Aplicación de efectos de relleno degradado

todo:imagen_alternativa_texto

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

Configuración de ajustes de alineación

Cualquiera que haya usado Microsoft Excel para formatear celdas estará familiarizado con la configuración de alineación en Microsoft Excel.

Configuración de alineación en Microsoft Excel

todo:imagen_alternativa_texto

Como puede ver en la figura anterior, hay diferentes tipos de opciones de alineación:

Todas estas configuraciones de alineación son totalmente compatibles con Aspose.Cells y se analizan con más detalle a continuación.

Configuración de ajustes de alineación

Aspose.Cells proporciona una clase,Libro de trabajo , que representa un archivo de Excel. La clase Workbook contiene una WorksheetCollection que permite el acceso a cada hoja de trabajo en el archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase.

La clase Worksheet proporciona una colección Cells. Cada elemento de la colección Cells representa un objeto de laCell clase.

Aspose.Cells proporciona el método setStyle en elCell clase que se utiliza para formatear una celda. ÉlEstilo class proporciona propiedades útiles para configurar los ajustes de fuente.

Seleccione cualquier tipo de alineación de texto mediante la enumeración TextAlignmentType. Los tipos de alineación de texto predefinidos en la enumeración TextAlignmentType son:

Tipos de alineación de texto Descripción
Abajo Representa la alineación del texto inferior
Centro Representa la alineación del texto central
CenterAcross Representa el centro a lo largo de la alineación del texto
Repartido Representa la alineación de texto distribuida
Llenar Representa la alineación del texto de relleno
General Representa la alineación general del texto.
Justificar Representa justificar la alineación del texto
Izquierda Representa la alineación del texto a la izquierda
Derecha Representa la alineación correcta del texto.
Parte superior Representa la alineación del texto superior

Alineación horizontal

Utilizar elEstilo el método setHorizontalAlignment del objeto para alinear el texto horizontalmente.

El siguiente resultado se logra ejecutando el siguiente código de ejemplo:

Alinear el texto horizontalmente

todo:imagen_alternativa_texto

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

Alineamiento vertical

Utilizar elEstilo método setVerticalAlignment del objeto para alinear el texto verticalmente.

El siguiente resultado se logra cuando VerticalAlignment se establece en el centro.

Alinear el texto verticalmente

todo:imagen_alternativa_texto

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

Sangría

Es posible establecer el nivel de sangría del texto en una celda usando elEstilo método setIndentLevel del objeto.

El siguiente resultado se logra cuando IndentLevel se establece en 2.

Nivel de sangría ajustado a 2

todo:imagen_alternativa_texto

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

Orientación

Establecer la orientación (rotación) del texto en una celda con elEstilo método setRotationAngle del objeto.

El siguiente resultado se logra cuando el ángulo de rotación se establece en 25.

Ángulo de rotación establecido en 25

todo:imagen_alternativa_texto

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

Control de texto

La siguiente sección explica cómo controlar el texto configurando el ajuste de texto, reducir para ajustar y otras opciones de formato.

Texto de ajuste

Envolver texto en una celda hace que sea más fácil de leer: la altura de la celda se ajusta para ajustarse a todo el texto, en lugar de cortarlo o extenderse a las celdas adyacentes.

Active o desactive el ajuste de texto con elEstilo método setTextWrapped del objeto.

El siguiente resultado se logra cuando el ajuste de texto está habilitado.

Texto envuelto dentro de la celda

todo:imagen_alternativa_texto

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

Encogimiento para encajar

Una opción para ajustar texto en un campo es reducir el tamaño del texto para que se ajuste a las dimensiones de una celda. Esto se hace configurando elEstilo propiedad IsTextWrapped del objeto paraverdadero.

El siguiente resultado se logra cuando el texto se reduce para que quepa en la celda.

Texto reducido para caber dentro de los límites de la celda

todo:imagen_alternativa_texto

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

Fusionando Cells

Al igual que Microsoft Excel, Aspose.Cells admite la combinación de varias celdas en una sola.

El siguiente resultado se logra si las tres celdas de la primera fila se fusionan para crear una sola celda grande.

Tres celdas fusionadas para crear una celda grande

todo:imagen_alternativa_texto

Utilizar elCells el método Merge de la colección para combinar celdas. El método Merge toma los siguientes parámetros:

  • Primera fila, la primera fila desde donde comenzar a fusionar.
  • Primera columna, la primera columna desde donde comenzar a fusionar.
  • Número de filas, el número de filas para fusionar.
  • Número de columnas, el número de columnas para fusionar.
// 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");

Dirección del texto

Es posible establecer el orden de lectura del texto en las celdas. El orden de lectura es el orden visual en el que se muestran los caracteres, palabras, etc. Por ejemplo, el inglés es un idioma de izquierda a derecha, mientras que el árabe es un idioma de derecha a izquierda.

El orden de lectura se establece con elEstilo propiedad TextDirection del objeto. Aspose.Cells proporciona tipos de dirección de texto predefinidos en la enumeración TextDirectionType.

Tipos de dirección de texto Descripción
Contexto El orden de lectura consistente con el idioma del primer carácter ingresado
De izquierda a derecha Orden de lectura de izquierda a derecha
De derecha a izquierda Orden de lectura de derecha a izquierda
// 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");

El siguiente resultado se logra si el orden de lectura del texto se establece de derecha a izquierda.

Configuración del orden de lectura de texto de derecha a izquierda

todo:imagen_alternativa_texto

Formateo de caracteres seleccionados en un Cell

Tratar con la configuración de fuentesexplicó cómo formatear celdas, pero solo cómo formatear el contenido de todas las celdas. ¿Qué sucede si desea formatear solo los caracteres seleccionados?

Aspose.Cells admite esta función. Este tema explica cómo utilizar esta característica.

Dar formato a los caracteres seleccionados

Aspose.Cells proporciona una clase,Libro de trabajo , que representa un archivo de Excel Microsoft. La clase Libro de trabajo contiene una colección de Hojas de trabajo que permite el acceso a cada hoja de trabajo en el archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase. La clase Worksheet proporciona una colección Cells. Cada elemento de la colección Cells representa un objeto de laCell clase.

La clase Cell proporciona un método de caracteres que toma los siguientes parámetros para seleccionar un rango de caracteres en una celda:

  • Índice de comienzo, el índice del carácter desde el que comenzar la selección.
  • Número de caracteres, el número de caracteres a seleccionar.

En el archivo de salida, en la celda A1", la palabra ‘Visita’ tiene el formato de fuente predeterminado pero ‘Aspose!’ es negrita y azul.

Formateo de caracteres seleccionados

todo:imagen_alternativa_texto

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

Activar hojas y hacer un activo Cell o seleccionar un rango de Cells en la hoja de trabajo

veces, es posible que deba activar una hoja de trabajo específica para que sea la primera que se muestre cuando alguien abra el archivo en Microsoft Excel. También es posible que deba activar una celda específica de tal manera que las barras de desplazamiento se desplacen a la celda activa para que sea claramente visible. Aspose.Cells es capaz de realizar todas las tareas mencionadas anteriormente.

Una hoja activa es la hoja en la que está trabajando en un libro de trabajo. El nombre en la pestaña de la hoja activa está en negrita por defecto. Mientras tanto, una celda activa es la celda que está seleccionada y en la que se ingresan los datos cuando comienza a escribir. Solo una celda está activa a la vez. La celda activa está rodeada por un borde grueso para que se vea contra las otras celdas. Aspose.Cells también le permite seleccionar un rango de celdas en la hoja de cálculo.

Activar una hoja y hacer un Cell activo

Aspose.Cells proporciona un API específico para estas tareas. Por ejemplo, el método WorksheetCollection.setActiveSheetIndex es útil para configurar una hoja activa. De manera similar, el método Worksheet.setActiveCell se usa para establecer y obtener una celda activa en una hoja de trabajo.

Si desea que las barras de desplazamiento horizontal y vertical se desplacen a la posición del índice de fila y columna para brindar una buena vista de los datos seleccionados cuando se abre el archivo en Microsoft Excel, use las propiedades Worksheet.setFirstVisibleRow y Worksheet.setFirstVisibleColumn.

El siguiente ejemplo muestra cómo activar una hoja de cálculo y activar una celda en ella. Las barras de desplazamiento se desplazan para hacer que la segunda fila y la segunda columna sean sus primeras filas y columnas visibles.

Configuración de la celda B2 como una celda activa

todo:imagen_alternativa_texto

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

Seleccionar un rango de Cells en la hoja de trabajo

Aspose.Cells proporciona el método Worksheet.selectRange(int startRow, int startColumn, int totalRows, int totalColumns, bool removeOthers). Usando el último parámetro - removeOthers - a verdadero, se eliminan otras selecciones de celdas o rangos de celdas en la hoja.

El siguiente ejemplo muestra cómo seleccionar un rango de celdas en la hoja de trabajo activa.

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

Formateo de filas y columnas

Dar formato a las filas y columnas de una hoja de cálculo para darle un aspecto al informe es posiblemente la función más utilizada de la aplicación Excel. Las API Aspose.Cells también brindan esta funcionalidad a través de su modelo de datos al exponer la clase Style, que maneja principalmente todas las funciones relacionadas con el estilo, como la fuente y sus atributos, la alineación del texto, los colores de fondo/primer plano, los bordes, el formato de visualización de números y literales de fecha, etc. . Otra clase útil que proporcionan las API Aspose.Cells es StyleFlag, que permite la reutilización del objeto Style.

En este artículo, intentaremos explicar cómo usar Aspose.Cells for Java API para aplicar formato a filas y columnas.

Formateo de filas y columnas

Aspose.Cells proporciona una clase,Libro de trabajo que representa un archivo de Excel Microsoft. ÉlLibro de trabajo class contiene una WorksheetCollection que permite el acceso a cada hoja de trabajo en el archivo de Excel. Una hoja de trabajo está representada por la clase Worksheet. ÉlHoja de cálculo class proporciona la colección Cells. La colección Cells proporciona una colección de Filas.

Dar formato a una fila

Cada elemento de la colección Rows representa un objeto Row. El objeto Row ofrece el método applyStyle que se usa para aplicar formato a una fila.

Para aplicar el mismo formato a una fila, use el objeto Estilo:

  1. Agregue un objeto Style a la clase Workbook llamando a su método createStyle.
  2. Establezca las propiedades del objeto Estilo para aplicar la configuración de formato.
  3. Asigne el objeto Style configurado al método applyStyle de un objeto 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");

Dar formato a una columna

La colección Cells proporciona una colección Columnas. Cada elemento de la colección Columns representa un objeto Column. Similar al objeto Row, el objeto Column ofrece el método applyStyle que se utiliza para establecer el formato de la columna. Use el método applyStyle del objeto Column para formatear una columna de la misma manera que una fila.

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

Configuración del formato de visualización de Numbers y fechas para filas y columnas

Si el requisito es establecer el formato de visualización de números y fechas para una fila o columna completa, entonces el proceso es más o menos el mismo que se discutió anteriormente, sin embargo, en lugar de establecer parámetros para el contenido textual, configurará el formato de los números. y fechas usando Style.Number o Style.Custom. Tenga en cuenta que la propiedad Style.Number es de tipo entero y hace referencia a los formatos integrados de número y fecha, mientras que la propiedad Style.Custom es de tipo cadena y acepta los patrones válidos.

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