首页 > 解决方案 > How can I edit column width with openpyxl

问题描述

I am trying to change the width of the first two columns in an excel sheet but I keep getting the following error:

wb.column_dimensions['A'].width = 25 AttributeError: 'Workbook' object has no attribute 'column_dimensions'

Here's my code:

from openpyxl import Workbook

wb = Workbook()
sheet = wb.active
wb.column_dimensions['A'].width = 25
wb.column_dimensions['B'].width = 25
sheet["A1"] = "Date"
sheet["B2"] = "Name"

标签: pythonexcelopenpyxl

解决方案


You need to address sheet like this:

from openpyxl import Workbook

wb = Workbook()
sheet = wb.active
sheet.column_dimensions['A'].width = 25
^
sheet.column_dimensions['B'].width = 25
^
sheet["A1"] = "Date"
sheet["B2"] = "Name"

推荐阅读