Writing Multi-line Strings Into Excel Cells in Python

Multi-line strings can come in two forms in Excel files (shown by B and C in the Figure below). In B, the sentence is broken word by word so that each word appears in its line, whereas, in C, text wrapping is implemented.

Neither text breaking nor line breaks are implemented in A; therefore, the sentence overflows the cell.

Text wrapping in Excel is a feature in which a word at the end of a line is automatically moved to the next line to keep the text within the cell width.

This article will discuss different ways of writing multi-line strings into excels through either text wrapping or line breaks.

Writing Multi-line Strings into Cells Using openpyxl

This package works for both line breaks and text wrapping. Additionally, it is suitable for editing already existing Excel files.

Implementing line breaks with openpyxl package

Line breaks are implemented using the “\n” – the new line character in Python. A string breaks at the position of the character.

The following code example shows how to implement line breaks on Excel cells with openpyxl.

Output (updated Excel file):

If you need to create a new file instead of updating an existing one, use the following code.

Be careful: If you use a path to a file that already exists, it will be overwritten without warning.

Writing multi-line string into Excel through text wrapping with openpyxl

The openpyxl supports formatting style for text wrapping. Here is an example,

Output (updated employees.xlsx file):

How to Create Multi-line Cells in Excel Using xlsxwriter Package

The xlsxwriter is another great package for writing data into Excel files. It is important, however, to note that xlsxwriter cannot be used to update existing files. Instead, this package is best for writing new Excel files into storage.

It cannot read or modify existing Excel XLSX files” – xlsxwriter documentation.

Be cautious: If you provide a path to a file that already exists, it will be overwritten with no warning.

Line breaks are implemented with the “\n” character like we did with openpyxl. The only difference is that, unlike openpyxl, xlsxwriter uses zero-based indexing for cell location. That is, the first cell is (0, 0) in xlsxwriter, but in openpyxl, it is (1,1)

Text-wrapping in xlsxwriter

Text-wrapping in xlsxwriter can be implemented, as shown in the example below.

Output (a view of file2.xlsx after writing to it):

Conclusion

This article discussed using openpyxl and xlsxwriter packages to write multi-line strings into Excel, which can be achieved using line breaking or text wrapping.

We also noted that openpyxl is the best choice for updating existing Excel files, while xlsxwriter is best used when writing data to a new Excel file.