计算单元格值的宽度和高度(以像素为单位)
Contents
[
Hide
]
有时需要计算单元格值的宽度和高度以适应内容,Aspose.Cells提供了Cell.getWidthOfValue()和Cell.getHeightOfValue()方法。使用这些方法,可以计算单元格内容的宽度和高度,然后相应设置列宽和行高,从而自动调整或适应内容。
另外,您还可以使用Aspose.Cells API来自动调整单元格或单元格范围的行和列。
计算单位为像素的单元格值的宽度和高度
以下代码示例演示如何使用Cell.getWidthOfValue()和Cell.getHeightOfValue()方法。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |