测量单元格值的宽度和高度,单位为像素。
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
const path = require("path"); | |
const AsposeCells = require("aspose.cells.node"); | |
// The path to the documents directory. | |
const dataDir = path.join(__dirname, "data"); | |
// Create workbook object | |
let workbook = new AsposeCells.Workbook(); | |
// Access first worksheet | |
let worksheet = workbook.getWorksheets().get(0); | |
// Access cell B2 and add some value inside it | |
let cell = worksheet.getCells().get("B2"); | |
cell.putValue("Welcome to Aspose!"); | |
// Enlarge its font to size 16 | |
let style = cell.getStyle(); | |
style.getFont().setSize(16); | |
cell.setStyle(style); | |
// Calculate the width and height of the cell value in unit of pixels | |
let widthOfValue = cell.getWidthOfValue(); | |
let heightOfValue = cell.getHeightOfValue(); | |
// Print both values | |
console.log("Width of Cell Value: " + widthOfValue); | |
console.log("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(path.join(dataDir, "output_out.xlsx")); |