的名单还有另一种解决方法,以模拟我发现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