我使用GetTextExtentPoint32W
獲取MS Excel 2010中單元格中文本的寬度。使用ActiveCell.Width
獲取單元格寬度。然後比較這兩個寬度以確定文本是否適合單元格或者延伸到單元格之外。從視覺上看,即使文本完全適合單元格,該方法返回的文本寬度也大於單元格寬度。另外,當我增加字體大小時,實際文本寬度與方法返回的寬度之間的差異增大。 以下是用於實現結果的源代碼的一部分。請幫我解決這個錯誤。在MS Excel中,由GetTextExtentPoint32W返回的單元格中文本的文本寬度大於實際寬度
hDC = ctypes.windll.user32.GetDC(self.windowHandle)
tempBMP = ctypes.windll.gdi32.CreateCompatibleBitmap(hDC, 1, 1)
hBMP = ctypes.windll.gdi32.SelectObject(hDC, tempBMP)
iFontSize = self.excelCellObject.Font.Size
deviceCaps = ctypes.windll.gdi32.GetDeviceCaps(hDC, 90)
iFontSize = int(iFontSize)
iFontSize = ctypes.c_int(iFontSize)
iFontSize = ctypes.windll.kernel32.MulDiv(iFontSize, deviceCaps, 72)
iFontSize = iFontSize * -1
iFontWeight = 700 if self.excelCellObject.Font.Bold else 400
sFontName = self.excelCellObject.Font.Name
sFontItalic = self.excelCellObject.Font.Italic
sFontUnderline = True if self.excelCellObject.Font.Underline else False
sFontStrikeThrough = self.excelCellObject.Font.Strikethrough
#Create a font object with the correct size, weight and style
hFont = ctypes.windll.gdi32.CreateFontW(iFontSize,
0, 0, 0,
iFontWeight,
sFontItalic,
sFontUnderline,
sFontStrikeThrough,
False, False, False,
False, False,
sFontName)
#Load the font into the device context, storing the original font object
hOldFont = ctypes.windll.gdi32.SelectObject(hDC, hFont)
sText = self.excelCellObject.Text
log.io("\nText \t"+sText+"\n")
textLength = len(sText)
class structText(ctypes.Structure):
_fields_ = [("width", ctypes.c_int),
("height",ctypes.c_int)]
StructText = structText()
getTextExtentPoint = ctypes.windll.gdi32.GetTextExtentPoint32W
getTextExtentPoint.argtypes = [ctypes.c_void_p,
ctypes.c_char_p,
ctypes.c_int,
ctypes.POINTER(structText)]
getTextExtentPoint.restype = ctypes.c_int
#Get the text dimensions
a = ctypes.windll.gdi32.GetTextExtentPoint32W(hDC,
sText,
textLength,
ctypes.byref(StructText))
#Delete the font object we created
a = ctypes.windll.gdi32.DeleteObject(hFont)
a = ctypes.windll.gdi32.DeleteObject(tempBMP)
#Release the device context
a = ctypes.windll.user32.ReleaseDC(self.windowHandle, hDC)
textWidth = StructText.width
cellWidth = self.excelCellObject.Width
謝謝。
要麼使用'GetTextExtentPoint32A'與ANSI字符串,要麼解碼爲'unicode'使用'GetTextExtentPoint32W'。對於後者,在'argtypes'中使用'c_wchar_p'。 – eryksun
感謝@eryksun讓這篇文章可讀。我提出了你所建議的更改。這讓我更接近最終解決方案。我會很快發佈它。 –