Calcolare la larghezza e l altezza del valore della cella in unità di pixel
A volte è necessario calcolare la larghezza e l’altezza del valore della cella per adattare il valore della cella all’interno della cella. Aspose.Cells fornisce i metodi Cell.getWidthOfValue() e Cell.getHeightOfValue() a tale scopo. Utilizzando questi metodi è possibile calcolare la larghezza e l’altezza del valore della cella e quindi impostare rispettivamente la larghezza della colonna e l’altezza della riga di quella cella e ciò regolerà o adatterà quindi il valore della cella all’interno della cella.
In alternativa, è possibile anche regolare automaticamente righe e colonne della cella o intervallo di celle utilizzando le API di Aspose.Cells.
Calcolare la larghezza e l’altezza del valore della cella in unità di pixel
Il codice seguente spiega l’uso dei metodi Cell.getWidthOfValue() e 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"); |