Buscar datos

Encontrar celdas que contienen datos especificados

Usar Microsoft Excel

Microsoft Excel permite a los usuarios encontrar celdas en una hoja de trabajo que contienen datos específicos. Si seleccionas Editar en el menú Buscar en Microsoft Excel, verás un cuadro de diálogo donde puedes especificar el valor de búsqueda.

Aquí, estamos buscando el valor “Naranjas”. Aspose.Cells también permite a los desarrolladores encontrar celdas en la hoja de cálculo que contienen valores especificados.

Usando Aspose.Cells for Node.js via C++

Aspose.Cells proporciona una clase, Workbook, que representa un archivo de Microsoft Excel. La clase Workbook contiene una colección Workbook.getWorksheets() que permite acceder a cada hoja de cálculo en el archivo Excel. Una hoja de cálculo está representada por la clase Worksheet. La clase Worksheet proporciona una colección getCells() que representa todas las celdas en la hoja de cálculo. La colección Cells ofrece varios métodos para buscar celdas en una hoja que contienen datos definidos por el usuario. Algunos de estos métodos se discuten a continuación en más detalle.

Buscar celdas que contienen una fórmula

Los desarrolladores pueden encontrar una fórmula específica en la hoja llamando al método find de la colección Cells. Por lo general, el método find acepta tres parámetros:

  • Objeto: El objeto a buscar. El tipo debe ser int, double, DateTime, string, bool.
  • Celda anterior: La celda anterior con el mismo objeto. Este parámetro puede establecerse a null si la búsqueda comienza desde el principio.
  • FindOptions: Opciones para encontrar el objeto requerido.

Los ejemplos a continuación utilizan datos de hoja de cálculo para practicar los métodos de búsqueda:

const AsposeCells = require("aspose.cells.node");
const path = require("path");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Opening the Excel file
const workbook = new AsposeCells.Workbook(path.join(dataDir, "sampleFindingCellsContainingFormula.xlsx"));
// Accessing the first worksheet in the Excel file
const worksheet = workbook.getWorksheets().get(0);
// Instantiate FindOptions Object
const findOptions = new AsposeCells.FindOptions();
findOptions.setLookInType(AsposeCells.LookInType.Formulas);
// Finding the cell containing the specified formula
const cell = worksheet.getCells().find("=SUM(A5:A10)", null, findOptions);
// Printing the name of the cell found after searching worksheet
console.log("Name of the cell containing formula: " + cell.getName());

Encontrar datos o fórmulas utilizando FindOptions

Es posible encontrar valores especificados usando el método Cells.find(object, Cell) de la colección Cells con varios FindOptions. Por lo general, el método find acepta los siguientes parámetros:

  • Valor de búsqueda, los datos o valores a buscar.
  • Celda anterior, la última celda que contenía el mismo valor. Este parámetro puede establecerse en nulo al buscar desde el principio.
  • Opciones de búsqueda, las opciones de búsqueda.
const path = require("path");
const AsposeCells = require("aspose.cells.node");
// The path to the documents directory.
const sourceDir = path.join(__dirname, "data");
// Instantiate the workbook object
const workbook = new AsposeCells.Workbook(sourceDir + "sampleFindingDataOrFormulasUsingFindOptions.xlsx");
workbook.calculateFormula();
// Get Cells collection
const cells = workbook.getWorksheets().get(0).getCells();
// Instantiate FindOptions Object
const findOptions = new AsposeCells.FindOptions();
// Create a Cells Area
const ca = new AsposeCells.CellArea();
ca.startRow = 8;
ca.startColumn = 2;
ca.endRow = 17;
ca.endColumn = 13;
// Set cells area for find options
findOptions.setRange(ca);
// Set searching properties
findOptions.setSearchBackward(false);
findOptions.setSearchOrderByRows(true);
// Set the lookintype, you may specify, values, formulas, comments etc.
findOptions.setLookInType(AsposeCells.LookInType.Values);
// Set the lookattype, you may specify Match entire content, endswith, starwith etc.
findOptions.setLookAtType(AsposeCells.LookAtType.EntireContent);
// Find the cell with value
const cell = cells.find(341, null, findOptions);
if (cell !== null) {
console.log("Name of the cell containing the value: " + cell.getName());
} else {
console.log("Record not found ");
}

Encontrar celdas que contengan un valor de cadena o número especificado

Es posible encontrar valores de cadena especificados llamando al mismo método find que se encuentra en la colección Cells con varios FindOptions.

Especifica las propiedades FindOptions.setLookInType y FindOptions.setLookAtType. El siguiente ejemplo de código ilustra cómo usar estas propiedades para buscar celdas con varias cadenas al principio, en el centro o al final de la cadena de la celda.

const path = require("path");
const AsposeCells = require("aspose.cells.node");
// The path to the documents directory.
const dataDir = path.join(__dirname, "data");
// Instantiate the workbook object
const workbook = new AsposeCells.Workbook(path.join(dataDir, "book1.xls"));
// Get Cells collection
const cells = workbook.getWorksheets().get(0).getCells();
const opts = new AsposeCells.FindOptions();
opts.setLookInType(AsposeCells.LookInType.Values);
opts.setLookAtType(AsposeCells.LookAtType.EntireContent);
// Find the cell with the input integer or double
let cell1 = cells.find(205, null, opts);
if (cell1 !== null) {
console.log("Name of the cell containing the value: " + cell1.getName());
} else {
console.log("Record not found ");
}
// Find the cell with the input string
let cell2 = cells.find("Items A", null, opts);
if (cell2 !== null) {
console.log("Name of the cell containing the value: " + cell2.getName());
} else {
console.log("Record not found ");
}
// Find the cell containing the input string
opts.setLookAtType(AsposeCells.LookAtType.Contains);
let cell3 = cells.find("Data", null, opts);
if (cell3 !== null) {
console.log("Name of the cell containing the value: " + cell3.getName());
} else {
console.log("Record not found ");
}

Temas avanzados