在字符单位和像素(点)之间转换Excel列宽

问题描述 投票:0回答:1

"One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used."

因此[Excel中的ColumnWidth被测量为适合列的“ 0”字符的数量。如何将该值转换为像素,反之亦然?

Image from https://bettersolutions.com/excel/rows-columns/column-widths.htm

excel unit-conversion
1个回答
0
投票

如前所述,Excel中的ColumnWidth值取决于可以通过Workbook.Styles("Normal").Font获得的工作簿的默认字体。另外,它取决于当前屏幕的DPI。

[在Excel 2013中对不同字体和大小进行了一些研究之后,我发现我们有2个线性函数(Arial无法看到,因为它与Tahoma重叠。)]

enter image description here

从图片中可以看出,ColumnWidth < 1的功能与折线图的主要部分不同。它的计算方式是:一列中的像素数/一列中适合一个“ 0”字符所需的像素数。

现在让我们看看典型的单元格宽度由什么组成。

enter image description here

  • [A-常规样式中的字符宽度为“ 0”
  • B-左右填充
  • [C-1px右边距

A可以使用GetTextExtentPoint32 Windows API函数进行计算,但是字体大小应该稍大一些。通过实验,我选择了+ 0.3pt,它对我使用的基本字体为8-48pt的不同字体有效。使用B(A + 1) / 4四舍五入为整数。另外,这里还需要屏幕DPI(请参阅下面的Python 3实现)

这里是用于字符像素转换的方程式及其在Python 3中的实现:

"round half up"

enter image description here

enter image description here

enter image description here
© www.soinside.com 2019 - 2024. All rights reserved.