Proper row height and column width are essential for optimizing data readability and ensuring that all content is fully visible in Excel. While the default row height and column width settings may be suitable in some cases, they may not be sufficient when dealing with lengthy text, large numbers, or complex formulas. In such cases, it becomes necessary to set appropriate row heights and column widths. In this article, we will explain how to set row height and column width in Excel in Python using Spire.XLS for Python.
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Set Row Height in Excel in Python
Spire.XLS for Python provides the Worksheet.SetRowHeight() method to set the height for a specific row. The detailed steps are as follows:
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[] property.
- Set the height of a specific row using Worksheet.SetRowHeight() method.
- Save the resulting file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * # Create a Workbook object workbook = Workbook() # Load an Excel file workbook.LoadFromFile("Sample.xlsx") # Get the first worksheet worksheet = workbook.Worksheets[0] # Set the height of the first row worksheet.SetRowHeight(1, 25) # Save the resulting file workbook.SaveToFile("SetRowHeight.xlsx", ExcelVersion.Version2016) workbook.Dispose()
Set Column Width in Excel in Python
To set the width of a specific column, you can use the Worksheet.SetColumnWidth() method. The detailed steps are as follows:
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[] property.
- Set the width of a specific column using Worksheet.SetColumnWidth() method.
- Save the resulting file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * # Create a Workbook object workbook = Workbook() # Load an Excel file workbook.LoadFromFile("Sample.xlsx") # Get the first worksheet worksheet = workbook.Worksheets[0] # Set the width of the third column worksheet.SetColumnWidth(3, 15) # Save the resulting file workbook.SaveToFile("SetColumnWidth.xlsx", ExcelVersion.Version2016) workbook.Dispose()
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.