Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python调整Excel文档中的列大小_Python_Excel_Python 2.7_Openpyxl - Fatal编程技术网

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

使用Python调整Excel文档中的列大小,python,excel,python-2.7,openpyxl,Python,Excel,Python 2.7,Openpyxl,我目前正在用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)

我目前正在用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
def writerow(self,vals):
ws=self.workbook.active
此行=self.numrows
此列=1
对于VAL中的v:
cell=ws.cell(行=此行,列=此列)
单元格值=v
如果ws.column\u维度[获取列字母(此列)]
我找到了我正在从事的工作所需要的东西。 我需要在检查或分配列宽的区域中添加“.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
def writerow(self,vals):
ws=self.workbook.active
此行=self.numrows
此列=1
对于VAL中的v:
cell=ws.cell(行=此行,列=此列)
单元格值=v
打印“列宽:”
打印ws.column\u维度[获取列字母(此列)]。宽度
如果ws.column_维度[获取_column_字母(此列)]。宽度
Excel列的大小不按字母数确定。那是你的问题。如果您使用的是单空间字体,您可以很好地估计缩放因子,但否则您必须猜测宽度值。您应该使用用于处理Excel文件的Python包标记您的问题。(或者在代码片段中包含相关的
import
语句,或者在问题文本中提到它。)我没有想到@JohnY。谢谢你让它工作起来了。FWIW我可能会将大小代码从循环中取出,并在之前或之后执行。如果您希望获得与文本大小匹配的宽度,请将其存储在列表中,然后将其最大化()。如上所述,尺寸始终是唯一的最佳猜测。