我刚刚实现了一个包装器类,该类可以在您输入物品时跟踪它们的宽度。看来效果很好。
import arial10class FitSheetWrapper(object): """Try to fit columns to max size of any entry. To use, wrap this around a worksheet returned from the workbook's add_sheet method, like follows: sheet = FitSheetWrapper(book.add_sheet(sheet_name)) The worksheet interface remains the same: this is a drop-in wrapper for auto-sizing columns. """ def __init__(self, sheet): self.sheet = sheet self.widths = dict() def write(self, r, c, label='', *args, **kwargs): self.sheet.write(r, c, label, *args, **kwargs) width = arial10.fitwidth(label) if width > self.widths.get(c, 0): self.widths[c] = width self.sheet.col(c).width = width def __getattr__(self, attr): return getattr(self.sheet, attr)
所有的魔力都在杨John的
arial10模块中。对于默认的Excel字体Arial
10,它具有良好的宽度。如果要使用其他字体编写工作表,则需要更改fitwidth函数,最好考虑
style传递给的参数
FitSheetWrapper.write。



