How to change or modify column width size in Openpyxl
Microsoft Excel is one of the most widely used tools today. Most software projects intend to use it for organizing data. Thus it becomes necessary to have easy ways to access Excel sheets without opening the application every time. Python provides you ways to operate on excel without directly opening the software, through the openpyxl library.
By now, you may be familiar with the various operations you can perform using openpyxl. ( iter_rows, fill cells with colors using openpyxl)
This tutorial will teach you how to modify column width size in openpyxl.
Installing openpyxl
First of all, you must make sure to install the openpyxl library. You can do the same by running the below command on your terminal.
pip install openpyxl
How to install openpyxl in Python
To change or modify column width size
In order to change the column width size, you can make use of the column_dimesnsions method of the worksheet class.
Syntax: worksheet.column_dimensions[column name].width=size
Let us look into the same with example below.
Consider an existing excel file codespeedy.xlsx as shown below;
So, now let us change the column size of column A;
import openpyxl worksheet = openpyxl.load_workbook("codespeedy.xlsx") sheet = worksheet.active sheet.column_dimensions['A'].width = 20 worksheet.save("codespeedy1.xlsx")
As you can see, we have modified the column size of A to 20 and saved the file after modification as codespeedy1.xlsx.
Similarly, you can also modify the column width of many rows as shown;
import openpyxl worksheet = openpyxl.load_workbook("codespeedy.xlsx") sheet = worksheet.active sheet.column_dimensions['A'].width = 20 sheet.column_dimensions['C'].width = 20 sheet.column_dimensions['E'].width = 30 worksheet.save("codespeedy1.xlsx")
Well, isn’t it amazing how you can manage such significant changes with such simple, small lines of code? Well, that in itself is the beauty of Python.
Also, check out Python Program to Merge Excel Cells using openpyxl.
Leave a Reply