的名單還有另一種解決方法,以模擬我發現Github site of xlsxwriter自動調整。我修改它返回水平文本(列寬)或90°旋轉的文本(行高度)的近似大小:
from PIL import ImageFont
def get_cell_size(value, font_name, font_size, dimension="width"):
""" value: cell content
font_name: The name of the font in the target cell
font_size: The size of the font in the target cell """
font = ImageFont.truetype(font_name, size=font_size)
(size, h) = font.getsize(str(value))
if dimension == "height":
return size * 0.92 # fit value experimentally determined
return size * 0.13 # fit value experimentally determined
這並不解決粗體文字或其他格式元素可能影響文本尺寸。否則,它工作得很好。
要查找列寬度自動調整:
def get_col_width(data, font_name, font_size, min_width=1):
""" Assume 'data' to be an iterable (rows) of iterables (columns/cells)
Also, every cell is assumed to have the same font and font size.
Returns a list with the autofit-width per column """
colwidth = [min_width for col in data[0]]
for x, row in enumerate(data):
for y, value in enumerate(row):
colwidth[y] = max(colwidth[y], get_cell_size(value, font_name, font_size))
return colwidth
試圖設置自動寬度也不是那麼簡單。字形寬度取決於字體。而如果你寫方程到單元格中呢?然後,根據寫入的內容,您無法確定單元格的寬度。單位是任意的,這是真的,但有一個實際的定義!一個單位接近默認字體中一個字符的寬度。請參閱https://support.microsoft.com/en-us/kb/214123 – 2015-07-24 15:12:03
有關xlwt的相關問題(對於XlsxWriter,總體方法將與此相同;儘管您可能需要Calibri 11而不是Arial 10的寬度) :http://stackoverflow.com/questions/6929115/python-xlwt-accessing-existing-cell-content-auto-adjust-column-width/23946840 – 2016-05-13 15:37:00