Adjusting Cell Width and Height
Sometimes, the content of a cell is displayed as #####
.
This occurs when the cell's width is too narrow to display the cell's data.
When working with Excel, you may need to adjust the width
and height
of cells to ensure that the data within them is fully visible.
In this lesson, we'll learn how to adjust the cell width and height using openpyxl.
Adjusting Cell Width
Cell width is typically adjusted based on the number of characters.
You can adjust the cell width using the width
property of the column_dimensions
attribute as shown below.
from openpyxl import Workbook
# Create a new workbook
wb = Workbook()
# Select the active sheet
ws = wb.active
# Enter data in the cell
ws['A1'] = "Data"
# Adjust cell width
ws.column_dimensions['A'].width = 20
# Save file
wb.save("output_file.xlsx")
In the code above, ws.column_dimensions['A'].width = 20
sets the width of column A to 20.
Here, 20 represents the average number of characters that can fit in the column based on the default font's average character width.
So, a width of 20 means that the cell can approximately fit 20 characters of the default font size.
Adjusting Cell Height
Sometimes, the data in a cell is too large, and you may need to adjust the height of the cell.
You can adjust the cell height using the height
property of the row_dimensions
attribute.
from openpyxl import Workbook
# Create a new workbook
wb = Workbook()
# Select the active sheet
ws = wb.active
# Enter data in the cell
ws['A1'] = "Data"
# Adjust cell height
ws.row_dimensions[1].height = 30
# Save file
wb.save("output_file.xlsx")
In the code above, ws.row_dimensions[1].height = 30
sets the height of row 1 to 30.
The unit for 30 is points (pt)
, which is the same unit used for setting font size.
For example, a cell height of 30 means 30 points, which is approximately 0.42 cm.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.