测量单元格值的宽度和高度,单位为像素。
Contents
[
Hide
]
有时候您需要计算单元格值的宽度和高度,以使单元格值适合单元格内。Aspose.Cells 为此目的提供了 Cell.GetWidthOfValue() 和 Cell.GetHeightOfValue() 方法。通过使用这些方法,您可以计算单元格值的宽度和高度,然后分别设置该单元格的列宽和行高,从而调整或使单元格值适合单元格内。
或者,您也可以使用 Aspose.Cells APIs 自动调整单元格或单元格范围的行和列。
以下代码解释了 Cell.GetWidthOfValue() 和 Cell.GetHeightOfValue() 方法的使用。
This file contains 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-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create workbook object | |
Workbook workbook = new Workbook(); | |
// Access first worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Access cell B2 and add some value inside it | |
Cell cell = worksheet.Cells["B2"]; | |
cell.PutValue("Welcome to Aspose!"); | |
// Enlarge its font to size 16 | |
Style style = cell.GetStyle(); | |
style.Font.Size = 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 | |
Console.WriteLine("Width of Cell Value: " + widthOfValue); | |
Console.WriteLine("Height of Cell Value: " + heightOfValue); | |
// Set the row height and column width to adjust/fit the cell value inside cell | |
worksheet.Cells.SetColumnWidthPixel(1, widthOfValue); | |
worksheet.Cells.SetRowHeightPixel(1, heightOfValue); | |
// Save the output excel file | |
workbook.Save(dataDir + "output_out.xlsx"); |