使用 Python 调整 Excel 文档中的列大小

Resize columns in Excel document with Python

我目前正在 Python 中创建一个 Excel 文档。我创建了 excel 文档,但我不确定代码有什么问题,它没有正确调整列的大小。有人有什么想法吗?

def writerow(self, vals):
    ws = self.workbook.active
    this_row = self.numrows
    this_col = 1
    for v in vals:
        cell = ws.cell(row = this_row, column = this_col)
        cell.value = v
        if ws.column_dimensions[get_column_letter(this_col)] < len(str(v)):
            ws.column_dimensions[get_column_letter(this_col)] = len(str(v))
        this_col += 1
    self.numrows += 1
    self.worksheet = ws

我找到了我所需要的东西。 我需要在检查或指定列宽的区域添加“.width”。

 def writerow(self, vals):
    ws = self.workbook.active
    this_row = self.numrows
    this_col = 1
    for v in vals:
        cell = ws.cell(row = this_row, column = this_col)
        cell.value = v
        print "Column Width:"
        print ws.column_dimensions[get_column_letter(this_col)].width
        if ws.column_dimensions[get_column_letter(this_col)].width < len(str(v)):
            ws.column_dimensions[get_column_letter(this_col)].width = len(str(v))
        this_col += 1
    self.numrows += 1
    self.worksheet = ws