Python: Wrap or Unwrap Text in Excel Cells

Text wrapping and unwrapping are powerful formatting options in Microsoft Excel that offer flexibility in displaying text within cells. When text wrapping is enabled, long text is automatically wrapped into multiple lines within a cell, which ensures that the entire content is visible without truncation. This feature is particularly useful for presenting lengthy descriptions, notes, or paragraphs within a confined cell space. On the other hand, text unwrapping allows you to remove line breaks and display the text in a single line within the cell. This can be beneficial in scenarios where you need to fit the text into a specific layout or when exporting data to other applications or file formats that may not handle wrapped text correctly. In this article, we will demonstrate how to wrap or unwrap text in Excel cells 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

Wrap or Unwrap Text in Excel Cells in Python

Spire.XLS for Python provides the CellStyle.WrapText property to control whether the text should be wrapped or unwrapped within a cell. If you want to wrap text in a cell, you can set the property as True. Conversely, if you want to unwrap text in a cell, you can set the property as False.

The following steps explain how to wrap or unwrap text in an Excel cell using Spire.XLS for Python:

  • Create a Workbook object.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Get a specified cell using Worksheet.Range[] property.
  • Get the style of the specified cell using CellRange.Style property.
  • Wrap the text in the cell by setting the CellStyle.WrapText property to True. Or unwrapping the text in the cell by setting the CellStyle.WrapText property to False.
  • 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 a sample Excel file
workbook.LoadFromFile("Sample.xlsx")

# Get the first worksheet of the file
sheet = workbook.Worksheets[0]

# Wrap the text in cell B3
sheet.Range["B3"].Style.WrapText = True

# Unwrap the text in cell B7
sheet.Range["B7"].Style.WrapText = False

#Save the resulting file
workbook.SaveToFile("WrapOrUnwrapTextInCells.xlsx", ExcelVersion.Version2013)
workbook.Dispose()

Python: Wrap or Unwrap Text in Excel Cells

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.