【问题标题】:Why "column width" is set to a different value?为什么“列宽”设置为不同的值?
【发布时间】:2021-03-18 06:49:54
【问题描述】:

我正在尝试在现有的 Excel 工作簿中设置 100 × 100 单元格的尺寸(高度和宽度),但无法将列的宽度设置为正确的值(尽管行高设置为正确的值) .我正在尝试将列宽设置为10,但在打开实际的 Excel 文件后,列宽变为9.29。我做错了什么?

from os import name
import openpyxl
from openpyxl.descriptors.base import DateTime
from openpyxl.utils import get_column_letter
import datetime


def format_wb(wb):
    for ws in wb.sheetnames:
        for i in range(1, 101):
            wb[ws].column_dimensions[get_column_letter(i)].width = 10
            wb[ws].row_dimensions[i].height = 20

    return wb


def main():
    file_name = "test"
    wb = openpyxl.load_workbook(f"{file_name}.xlsx")
    wb = format_wb(wb)
    wb.save(f"{file_name}.xlsx")


if __name__ == "__main__":
    main()

【问题讨论】:

    标签: python python-3.x excel openpyxl


    【解决方案1】:

    [编辑] 我认为这是一个更令人满意的解释:

    "在 Excel 中,xml 存储的值和为用户显示的值应该不同,并且取决于主题中选择的默认字体(Colibri 差异为 0.7109375)。

    openpyxl 不加载默认字体信息,它创建的 Excel 文件使用相同的默认字体 (Colibri 11)。

    因此,对于使用openpyxl 保存的文件,0.7109375 是恒定的。"

    来源:https://foss.heptapod.net/openpyxl/openpyxl/-/issues/293


    据我了解,您的代码没有任何问题。 最近遇到了同样的问题,凭经验发现,如果您希望 Excel 中的列宽等于整数(在您的情况下为 10),则必须使用 openpyxl 将其设置为该数字 + 0.71(在您的情况下为 10.71)。

    【讨论】:

    • 是的,这正是我正在做的一段时间,但这是绕着陷阱走。
    猜你喜欢
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2011-10-28
    • 2017-03-07
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多