Rangos con nombre
Creación de un rango con nombre
Usando Microsoft Excel
Los siguientes pasos describen cómo nombrar una celda o rango de celdas usando Microsoft Excel. Este método se aplica a Microsoft Office Excel 2003, Microsoft Excel 97, 2000 y 2002.
- Seleccione la celda, rango de celdas que desea nombrar.
- Haga clic en el Cuadro de nombre en el extremo izquierdo de la barra de fórmulas.
- Escriba el nombre de las celdas.
- Presione ENTRAR.
Usando Aspose.Cells
Aquí, usamos el Aspose.Cells API para hacer la tarea.
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 la clase proporciona unCellsrecopilación.
Es posible crear un rango con nombre llamando al sobrecargadocrearRango método de laCells recopilación. Una versión típica de lacrearRango método toma los siguientes parámetros:
- Nombre de la celda superior izquierda, el nombre de la celda superior izquierda en el rango.
- Nombre de la celda inferior derecha, el nombre de la celda inferior derecha en el rango.
Cuando elcrearRango se llama al método, devuelve el rango con nombre recién creado como una instancia deRango clase.
El siguiente ejemplo muestra cómo crear un rango de celdas con nombre que se extiende sobre B4:G14.
// 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(CreateNamedRangeofCells.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Accessing the first worksheet in the Excel file | |
Worksheet sheet = worksheets.get(0); | |
Cells cells = sheet.getCells(); | |
// Creating a named range | |
Range namedRange = cells.createRange("B4", "G14"); | |
namedRange.setName("TestRange"); | |
// Saving the modified Excel file in default (that is Excel 2000) format | |
workbook.save(dataDir + "CNROfCells_out.xls"); | |
// Print message | |
System.out.println("Process completed successfully"); |
Acceso a todos los rangos con nombre en una hoja de cálculo
Llama aobtenerRangosNombrados método de laColección de hojas de trabajo para obtener todos los rangos con nombre en una hoja de cálculo. ÉlobtenerRangosNombrados devuelve una matriz de todos los rangos con nombre en elColección de hojas de trabajo.
El siguiente ejemplo muestra cómo acceder a todos los rangos con nombre en un libro de trabajo.
// 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(AccessAllNamedRanges.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Accessing the first worksheet in the Excel file | |
Worksheet sheet = worksheets.get(0); | |
Cells cells = sheet.getCells(); | |
// Getting all named ranges | |
Range[] namedRanges = worksheets.getNamedRanges(); | |
// Print message | |
System.out.println("Number of Named Ranges : " + namedRanges.length); |
Acceder a un rango con nombre específico
Llama aColección de hojas de trabajo colecciónobtenerRangoPorNombre método para obtener un rango específico por nombre. un tipicoobtenerRangoPorNombre toma el nombre del rango con nombre y devuelve el rango con nombre especificado como una instancia delRangoclase.
El siguiente ejemplo muestra cómo acceder a un rango específico por su nombre.
// 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(AccessSpecificNamedRange.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Accessing the first worksheet in the Excel file | |
Worksheet sheet = worksheets.get(0); | |
Cells cells = sheet.getCells(); | |
// Getting the specified named range | |
Range namedRange = worksheets.getRangeByName("TestRange"); | |
// Print message | |
System.out.println("Named Range : " + namedRange.getRefersTo()); |
Identificar Cells en un rango con nombre
Usando Aspose.Cells, puede insertar datos en las celdas individuales de un rango. Supongamos que tiene un rango de celdas con nombre, es decir, A1: C4. Entonces, la matriz haría 4 * 3 = 12 celdas y las celdas de rango individuales se organizan secuencialmente. Aspose.Cells le proporciona algunas propiedades útiles de la clase Rango para acceder a las celdas individuales del rango. Puede usar los siguientes métodos para identificar las celdas en el rango:
- obtenerPrimeraFila devuelve el índice de la primera fila en el rango con nombre.
- getFirstColumndevuelve el índice de la primera columna en el rango con nombre.
El siguiente ejemplo muestra cómo ingresar algunos valores en las celdas de un rango específico.
// 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(IdentifyCellsinNamedRange.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(dataDir + "book1.xls"); | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Accessing the first worksheet in the Excel file | |
Worksheet sheet = worksheets.get(0); | |
Cells cells = sheet.getCells(); | |
// Getting the specified named range | |
Range range = worksheets.getRangeByName("TestRange"); | |
// Identify range cells. | |
System.out.println("First Row : " + range.getFirstRow()); | |
System.out.println("First Column : " + range.getFirstColumn()); | |
System.out.println("Row Count : " + range.getRowCount()); | |
System.out.println("Column Count : " + range.getColumnCount()); |
Ingrese datos en el Cells en el rango con nombre
Usando Aspose.Cells, puede insertar datos en las celdas individuales de un rango. Suponga que tiene un rango de celdas con nombre, es decir, H1: J4. Entonces, la matriz haría 4 * 3 = 12 celdas y las celdas de rango individuales se organizan secuencialmente. Aspose.Cells le proporciona algunas propiedades útiles de la clase Rango para acceder a las celdas individuales del rango. Puede usar las siguientes propiedades para identificar las celdas en el rango:
- obtenerPrimeraFiladevuelve el índice de la primera fila en el rango con nombre.
- getFirstColumndevuelve el índice de la primera columna en el rango con nombre.
El siguiente ejemplo muestra cómo ingresar algunos valores en las celdas de un rango específico.
// 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(InputDataInCellsInRange.class) + "data/"; | |
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook(); | |
// Get the first worksheet in the workbook. | |
Worksheet worksheet1 = workbook.getWorksheets().get(0); | |
// Create a range of cells and specify its name based on H1:J4. | |
Range range = worksheet1.getCells().createRange("H1:J4"); | |
range.setName("MyRange"); | |
// Input some data into cells in the range. | |
range.get(0, 0).setValue("USA"); | |
range.get(0, 1).setValue("SA"); | |
range.get(0, 2).setValue("Israel"); | |
range.get(1, 0).setValue("UK"); | |
range.get(1, 1).setValue("AUS"); | |
range.get(1, 2).setValue("Canada"); | |
range.get(2, 0).setValue("France"); | |
range.get(2, 1).setValue("India"); | |
range.get(2, 2).setValue("Egypt"); | |
range.get(3, 0).setValue("China"); | |
range.get(3, 1).setValue("Philipine"); | |
range.get(3, 2).setValue("Brazil"); | |
// Save the excel file. | |
workbook.save(dataDir + "IDICInRange_out.xls"); | |
// Print message | |
System.out.println("Process completed successfully"); |
Rangos de formato… Establecimiento de atributos de fuente y color de fondo en un rango con nombre
Para aplicar formato, defina unEstilo objeto para especificar la configuración de estilo y aplicarlo alRangoobjeto.
El siguiente ejemplo muestra cómo establecer un color de relleno sólido (color de sombreado) con configuración de fuente en un rango.
// 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(FormatRanges1.class) + "data/"; | |
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook(); | |
// Get the first worksheet in the book. | |
Worksheet WS = workbook.getWorksheets().get(0); | |
// Create a named range of cells. | |
com.aspose.cells.Range range = WS.getCells().createRange(1, 1, 1, 17); | |
range.setName("MyRange"); | |
// Declare a style object. | |
Style stl; | |
// Create the style object with respect to the style of a cell. | |
stl = WS.getCells().get(1, 1).getStyle(); | |
// Specify some Font settings. | |
stl.getFont().setName("Arial"); | |
stl.getFont().setBold(true); | |
// Set the font text color | |
stl.getFont().setColor(Color.getRed()); | |
// To Set the fill color of the range, you may use ForegroundColor with | |
// solid Pattern setting. | |
stl.setBackgroundColor(Color.getYellow()); | |
stl.setPattern(BackgroundType.SOLID); | |
// Apply the style to the range. | |
for (int r = 1; r < 2; r++) { | |
for (int c = 1; c < 18; c++) { | |
WS.getCells().get(r, c).setStyle(stl); | |
} | |
} | |
// Save the excel file. | |
workbook.save(dataDir + "FormatRanges1_out.xls"); | |
// Print message | |
System.out.println("Process completed successfully"); |
Rangos de formato… Adición de bordes a un rango con nombre
Es posible agregar bordes a un rango de celdas en lugar de a una sola celda. ÉlRango objeto proporciona un[establecerEsquemaFronteras](https://reference.aspose.com/cells/java/com.aspose.cells/range#setOutlineBorders(int,%20com.aspose.cells.Color)método que toma los siguientes parámetros para agregar un borde al rango de celdas:
- borderStyle: el tipo de borde, seleccionado de laTipo de borde de celdaenumeración.
- borderColor: el color de la línea del borde, seleccionado de laColor enumeración.
El siguiente ejemplo muestra cómo establecer un borde de contorno en un rango.
// 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(FormatRanges2.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Adding a new worksheet to the Workbook object | |
// Obtaining the reference of the newly added worksheet | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.setValue("Hello World From Aspose"); | |
// Creating a range of cells starting from "A1" cell to 3rd column in a | |
// row | |
Range range = worksheet.getCells().createRange("A1:C1"); | |
range.setName("MyRange"); | |
// Adding a thick outline border with the blue line | |
range.setOutlineBorders(CellBorderType.THICK, Color.getBlue()); | |
// Saving the Excel file | |
workbook.save(dataDir + "FormatRanges2_out.xls"); | |
// Print message | |
System.out.println("Process completed successfully"); |
El siguiente resultado se generaría después de ejecutar el código anterior:
Aplicar estilo a las celdas en un Rango
A veces, desea crear aplicar un estilo a las celdas en unRango . Para esto, puede iterar sobre las celdas en el rango y usar elCell.setStyle para aplicar el estilo a la celda.
El siguiente ejemplo muestra cómo aplicar estilos a las celdas de un rango.
// 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(ConvertCellsAddresstoRangeorCellArea.class) + "data/"; | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of the newly added worksheet | |
int sheetIndex = workbook.getWorksheets().add(); | |
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex); | |
// Accessing the "A1" cell from the worksheet | |
Cell cell = worksheet.getCells().get("A1"); | |
// Adding some value to the "A1" cell | |
cell.setValue("Hello World!"); | |
// Creating a range of cells based on cells Address. | |
Range range = worksheet.getCells().createRange("A1:F10"); | |
// Specify a Style object for borders. | |
Style style = cell.getStyle(); | |
// Setting the line style of the top border | |
style.setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, Color.getBlack()); | |
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THICK, Color.getBlack()); | |
style.setBorder(BorderType.LEFT_BORDER, CellBorderType.THICK, Color.getBlack()); | |
style.setBorder(BorderType.RIGHT_BORDER, CellBorderType.THICK, Color.getBlack()); | |
Iterator cellArray = range.iterator(); | |
while (cellArray.hasNext()) { | |
Cell temp = (Cell) cellArray.next(); | |
// Saving the modified style to the cell. | |
temp.setStyle(style); | |
} | |
// Saving the Excel file | |
workbook.save(dataDir + "CCAToROrCArea_out.xls"); |
Eliminar un rango con nombre
Aspose.Cells proporciona elNameCollection.RemoveAt() para borrar el nombre del rango. Para borrar el contenido del rango, utiliceCells.ClearRango() método. El siguiente ejemplo muestra cómo eliminar un rango con nombre con su contenido.
// 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(RemoveANamedRange.class) + "data/"; | |
// Instantiate a new Workbook. | |
Workbook workbook = new Workbook(); | |
// Get all the worksheets in the book. | |
WorksheetCollection worksheets = workbook.getWorksheets(); | |
// Get the first worksheet in the worksheets collection. | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Create a range of cells. | |
Range range1 = worksheet.getCells().createRange("E12", "I12"); | |
// Name the range. | |
range1.setName("MyRange"); | |
// Set the outline border to the range. | |
range1.setOutlineBorder(BorderType.TOP_BORDER, CellBorderType.MEDIUM, Color.fromArgb(0, 0, 128)); | |
range1.setOutlineBorder(BorderType.BOTTOM_BORDER, CellBorderType.MEDIUM, Color.fromArgb(0, 0, 128)); | |
range1.setOutlineBorder(BorderType.LEFT_BORDER, CellBorderType.MEDIUM, Color.fromArgb(0, 0, 128)); | |
range1.setOutlineBorder(BorderType.RIGHT_BORDER, CellBorderType.MEDIUM, Color.fromArgb(0, 0, 128)); | |
// Input some data with some formattings into | |
// a few cells in the range. | |
range1.get(0, 0).setValue("Test"); | |
range1.get(0, 4).setValue("123"); | |
// Create another range of cells. | |
Range range2 = worksheet.getCells().createRange("B3", "F3"); | |
// Name the range. | |
range2.setName("testrange"); | |
// Copy the first range into second range. | |
range2.copy(range1); | |
// Remove the previous named range (range1) with its contents. | |
worksheet.getCells().clearRange(11, 4, 11, 8); | |
worksheets.getNames().removeAt(0); | |
// Save the excel file. | |
workbook.save(dataDir + "RANRange_out.xls"); | |
// Print message | |
System.out.println("Process completed successfully"); |
bordecolores