Calcular el Ancho y Alto del Valor de la Celda en Unidades de Píxeles
A veces necesitas calcular el ancho y alto del valor de la celda para que quepa dentro de la celda. Aspose.Cells proporciona los métodos Cell.getWidthOfValue() y Cell.getHeightOfValue() para este propósito. Al utilizar estos métodos, puedes calcular el ancho y alto del valor de la celda y luego establecer el ancho de la columna y el alto de la fila de esa celda respectivamente, lo que ajustará o ajustará el valor de la celda dentro de la celda.
Alternativamente, también puedes ajustar automáticamente filas y columnas de tu celda o rango de celdas utilizando las APIs de Aspose.Cells.
Calcular el Ancho y Alto del Valor de la Celda en Unidades de Píxeles
El siguiente código explica el uso de Cell.getWidthOfValue() y los métodos Cell.getHeightOfValue().
// 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(CalculateWidthAndHeightOfCell.class); | |
// Create workbook object | |
Workbook workbook = new Workbook(); | |
// Access first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Access cell B2 and add some value inside it | |
Cell cell = worksheet.getCells().get("B2"); | |
cell.putValue("Welcome to Aspose!"); | |
// Enlarge its font to size 16 | |
Style style = cell.getStyle(); | |
style.getFont().setSize(16); | |
cell.setStyle(style); | |
// Calculate the width and height of the cell value in unit of pixels | |
int widthOfValue = cell.getWidthOfValue(); | |
int heightOfValue = cell.getHeightOfValue(); | |
// Print both values | |
System.out.println("Width of Cell Value: " + widthOfValue); | |
System.out.println("Height of Cell Value: " + heightOfValue); | |
// Set the row height and column width to adjust/fit the cell value inside cell | |
worksheet.getCells().setColumnWidthPixel(1, widthOfValue); | |
worksheet.getCells().setRowHeightPixel(1, heightOfValue); | |
// Save the output excel file | |
workbook.save(dataDir + "output.xlsx"); |