简体   繁体   English

openpyxl-更改n列的宽度

[英]openpyxl - change width of n columns

I am trying to change the column width for n number of columns. 我正在尝试更改n列的列宽。 I am able to do this for rows as per the below code. 我能够按照以下代码对行执行此操作。

rowheight = 2
while rowheight < 601:
    ws.row_dimensions[rowheight].height = 4
    rowheight += 1

The problem I have is that columns are in letters and not numbers. 我的问题是列是字母而不是数字。

As pointed out by ryachza the answer was to use an openpyxl utility, however the utility to use is get_column_letter and not column_index_from_string as I want to convert number to letter and not visa versa. 正如ryachza所指出的,答案是使用openpyxl实用程序,但是要使用的实用程序是get_column_letter而不是column_index_from_string因为我想将数字转换为字母,反之亦然。

Here is the working code 这是工作代码

from openpyxl.utils import get_column_letter

# Start changing width from column C onwards
column = 3
while column < 601:
    i = get_column_letter(column)
    ws.column_dimensions[i].width = 4
    column += 1

To get the column index, you should be able to use: 要获取列索引,您应该可以使用:

i = openpyxl.utils.column_index_from_string(?)

And then: 接着:

ws.column_dimensions[i].width = ?

Would it be possible to do this using slicing? 可以使用切片吗?

col_range = ws['C:F']
for col in col_range:
    ws.column_dimendions.width = 15

I do not have any error on my code but I cannot see the column width change on my workbook. 我的代码没有任何错误,但是在工作簿上看不到列宽的变化。

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

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