您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python xlwt-访问现有单元格内容,自动调整列宽

Python xlwt-访问现有单元格内容,自动调整列宽

我刚刚实现了一个包装器类,该类可以在您输入物品时跟踪它们的宽度。看来效果很好。

import arial10

class 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

python 2022/1/1 18:29:01 有434人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶