When creating instructional spreadsheets, dashboards, or annotated reports, cells alone are often insufficient for accommodating lengthy explanatory text or freely positioned notes. Excel's Text Box provides a container independent of the cell grid: it can be placed anywhere, hold multiple lines of text, have its own font and background settings, and leave the data and formulas in surrounding cells untouched.
When you need to programmatically generate such annotated spreadsheets in bulk, manipulating text boxes through code is far more efficient and consistent than drawing them by hand. This article walks through how to insert text boxes into Excel worksheets using Python, configure common properties such as text content, alignment, font, background, padding, and word wrap, as well as read and replace text within text boxes.
Why Use Text Boxes Instead of Regular Cells
Compared to placing explanatory text directly in cells, text boxes offer several practical advantages:
- Free positioning: They can float anywhere on the sheet, independent of the row-and-column structure.
- Independent styling: Font, color, background, and border can each be configured separately, decoupled from the main table style.
- Long-text support: They are ideal for displaying descriptions, annotations, legends, and other multi-line content, with word wrap to maintain layout.
- Easy find-and-replace: Text boxes can serve as template placeholder carriers, enabling bulk text population or replacement.
Prerequisites
Working with Excel text boxes can be done using Spire.XLS for Python, which can be installed via pip:
pip install Spire.Xls
Import the main and common modules in your script as follows:
from spire.xls import *
from spire.xls.common import *
Inserting a Text Box and Setting Text and Alignment
To insert a text box into a worksheet, use sheet.TextBoxes.AddTextBox(), passing the row, column, height, and width (all in Excel's internal units). Once inserted, you can write content via the Text property and control horizontal and vertical alignment through HAlignment and VAlignment.
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.Version = ExcelVersion.Version2013
sheet = workbook.Worksheets[0]
# Insert a text box at row 2, column 2, with height 18 and width 65 units
textbox = sheet.TextBoxes.AddTextBox(2, 2, 18, 65)
textbox.Text = "Spire.XLS for Python is a professional Excel Python API..."
textbox.HAlignment = CommentHAlignType.Center
textbox.VAlignment = CommentVAlignType.Center
workbook.SaveToFile("TextBox.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Note that the first two parameters of AddTextBox (row and column) determine which cell position the top-left corner of the text box is anchored to, while the last two parameters define the text box's own dimensions. These units differ from the cell's width and height units, so it's best to verify the visual result when setting these values.
Setting Font and Background
The text appearance of a text box is controlled through the RichText mechanism, which allows precise font control over a specific character range. The background is filled with a solid color via the Fill property.
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("Template_Xls_5.xlsx")
sheet = workbook.Worksheets[0]
shape = sheet.TextBoxes[0]
# Create a font and set its properties
font = workbook.CreateFont()
font.FontName = "Century Gothic"
font.Size = 10
font.IsBold = True
font.Color = Color.get_Blue()
# Apply the font to the entire text box text
rt = RichText(shape.RichText)
rt.SetFont(0, len(shape.Text) - 1, font)
# Set a solid color background
shape.Fill.FillType = ShapeFillType.SolidColor
shape.Fill.ForeKnownColor = ExcelColors.BlueGray
workbook.SaveToFile("SetFontAndBackground.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
The three parameters of RichText.SetFont(start, end, font) are the start index, end index, and font object, respectively. Indexing starts at 0 and is inclusive on both ends. To apply a uniform style to the entire text, simply use 0 to len(text) - 1 to cover all characters. For partial highlighting, pass the corresponding sub-range instead.
Setting Padding and Word Wrap
When a text box contains a large amount of text, you can control the spacing between the text and the border using inner margin properties, and enable word wrap via IsWrapText to prevent text overflow or visual crowding.
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("Template_Xls_4.xlsx")
sheet = workbook.Worksheets[0]
textbox = sheet.TextBoxes.AddTextBox(4, 2, 100, 300)
textbox.Text = "Inserting a Text Box in Excel with Internal Margins"
textbox.HAlignment = CommentHAlignType.Center
textbox.VAlignment = CommentVAlignType.Center
# Set internal margins of the text box
textbox.InnerLeftMargin = 1
textbox.InnerRightMargin = 3
textbox.InnerTopMargin = 1
textbox.InnerBottomMargin = 1
workbook.SaveToFile("SetInternalMarginOfTextbox.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
For an existing text box with lengthy content, simply enable word wrap directly:
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("TextBoxSampleB.xlsx")
sheet = workbook.Worksheets[0]
shape = sheet.TextBoxes[0]
shape.IsWrapText = True
workbook.SaveToFile("TextBoxWithWrapText.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Inner margin values are measured in points — the larger the value, the farther the text sits from the border. Word wrap causes the text box to reflow content within its set dimensions, and combining both features significantly improves the readability of long text.
Reading and Replacing Text in Text Boxes
Text boxes are accessible objects within the document. By iterating over sheet.TextBoxes, you can read or bulk-replace the text they contain, making this ideal for template placeholder population.
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
workbook.LoadFromFile("ReplaceTextInTextBox.xlsx")
sheet = workbook.Worksheets[0]
# Iterate through all text boxes and replace the specified text
for tb in sheet.TextBoxes:
if tb.Text != "" and "<TAG_1>" in tb.Text:
tb.Text = tb.Text.replace("<TAG_1>", "Spire.XLS for .NET")
workbook.SaveToFile("ReplaceTextInTextBox.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
If the document contains many text boxes, you can also assign names to them and locate specific boxes directly by name rather than relying on index positions:
from spire.xls import *
from spire.xls.common import *
workbook = Workbook()
sheet = workbook.Worksheets[0]
textbox = sheet.TextBoxes.AddTextBox(2, 2, 18, 65)
textbox.Name = "FirstTextBox"
textbox.Text = "Descriptive text to be retrieved later"
# Retrieve the text box by name
found = sheet.TextBoxes["FirstTextBox"]
print(found.Text)
workbook.Dispose()
Naming is especially useful when generating a large number of labeled text boxes. For example, you might name each annotation box "Note_CustomerInfo" or "Note_CostDescription" so that subsequent maintenance can target them precisely.
Practical Tips
-
Distinguish anchoring from sizing: In
AddTextBox(row, col, height, width), the row and column define the anchor point while height and width define the text box's own size. The two use different units, so start with small test values when first working with them. -
Check for empty text before replacing: When iterating and replacing, include a
tb.Text != ""check to avoid unexpected behavior from empty text boxes. - Coordinate font size and background: Pair light backgrounds with dark text and dark backgrounds with light text to improve text box readability in dense reports.
-
Release resources promptly: After batch-processing multiple workbooks, call
Dispose()to avoid file handle leaks.
Summary
This article covered common operations on Excel text boxes: inserting text boxes with text alignment, setting fonts and backgrounds, adjusting padding and word wrap, and reading and replacing text. The unified entry point for all these capabilities is the sheet.TextBoxes collection on the worksheet: AddTextBox() handles creation, Text and RichText manage content and styling, Fill controls the background, Inner*Margin and IsWrapText govern layout, and iteration or name-based access supports bulk maintenance.
Building on these foundations, you can combine text boxes with charts, shapes, data validation, and other features — for instance, adding annotated text boxes to charts or using text boxes to display dynamic prompts in dashboards — to make your automatically generated Excel documents both data-accurate and clearly documented.
Top comments (0)