openpyxl - 改变 n 列的宽度

openpyxl - change width of n columns

我正在尝试更改 n 列的列宽。 我可以按照以下代码对行执行此操作。

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

我遇到的问题是列是字母而不是数字。

要获取列索引,您应该可以使用:

i = openpyxl.utils.column_index_from_string(?)

然后:

ws.column_dimensions[i].width = ?

正如 ryachza 所指出的那样,答案是使用 openpyxl 实用程序,但是要使用的实用程序是 get_column_letter 而不是 column_index_from_string,因为我想将数字转换为字母而不是相反。

这是工作代码

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