简体   繁体   English

使用Python调整Excel文档中的列

[英]Resize columns in Excel document with Python

I am currently working with creating an Excel document in Python. 我目前正在使用Python创建Excel文档。 I create the excel document but I'm not sure what is wrong with the code that it is not resizing the columns correctly. 我创建了excel文档,但我不确定代码是什么问题,它没有正确调整列的大小。 Does anyone have any ideas? 有没有人有任何想法?

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

I found what I needed for what I am working on. 我找到了我正在做的工作所需要的东西。 I needed to add ".width" to the areas where I was checking or assigning column widths. 我需要在我检查或指定列宽的区域添加“.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM