Best Python Library for Generating Word Files

Alexander Stock
6 min readFeb 2, 2024

--

When it comes to document generation, particularly Word files, Python offers an array of libraries that simplify the process and enhance efficiency. These libraries empower developers to create, modify, and manipulate Word documents seamlessly, catering to diverse requirements from simple text-based documents to complex, formatted reports. Choosing the right Python library for generating Word files is crucial for a project’s success.

Over the past few months, I’ve tried the usual commercial and open source libraries on the market, and based on my personal experience, I think Spire.Doc for Python is one of the best libraries out there. It provides a comprehensive set of innovative APIs, allowing programmers to generate, modify, and extract content from Word documents with ease.

Python Word Processing Library

Using Spire.Doc, you can create new Word documents from scratch, load existing documents, perform various document operations such as adding or deleting sections, paragraphs, tables, images, headers, footers, and more. In addition to document creation and manipulation, Spire.Doc allows you to convert Word documents to different formats such as PDF, HTML, RTF, XML, and image files.

You can install Spire.Doc for Python in your Python application by running the following pip command.

pip install Spire.Doc

Classes and Methods for Working with Word Documents

Spire.Doc is an object-oriented Word processing component, enabling developers to manage various elements of a Word document with just a few lines of code. The nomenclature of classes, methods, and properties is straightforward and easily comprehensible. With a basic understanding of the structure and elements of Word documents, users can effortlessly leverage these functionalities. The subsequent table outlines key classes and methods within Spire.Doc.

classes and methods in spire.doc

Steps to Create a Word Document in Python

  1. Import the Spire.Doc library modules.
  2. Create a Document object.
  3. Add a section to the document.
  4. Add a paragraph to the section
  5. Add text, images or other elements to the paragraph.
  6. Save the document to a Doc or Docx file.

Having grasped the fundamental concepts, let’s explore six code snippets to acquire the skills of crafting a Word document. These snippets will guide you in adding paragraphs (text), pictures, tables, text boxes, and lists to your document. Additionally, you’ll learn how to load an existing document.

Create a Word Document in Python

from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Set the page margins
section.PageSetup.Margins.All = 40

# Add a title
title = section.AddParagraph()
title.AppendText("Create a Word File in Python")

# Add two paragraphs
paragraph = section.AddParagraph()
paragraph.AppendText("Spire.Doc for Python is a professional Python library designed for developers to " +
"create, read, write, convert, compare and print Word documents in Python applications " +
"with fast and high-quality performance.")

# Apply heading1 to the title
title.ApplyStyle(BuiltinStyle.Heading1)

# Create a style for the paragraph
style = ParagraphStyle(doc)
style.Name = "paraStyle"
style.CharacterFormat.FontName = "Arial"
style.CharacterFormat.FontSize = 13
doc.Styles.Add(style)
paragraph.ApplyStyle("paraStyle")

# Set the horizontal alignment of title and paragraph
title.Format.HorizontalAlignment = HorizontalAlignment.Center
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left

# Set the after spacing
title.Format.AfterSpacing = 10

# Save to file
doc.SaveToFile("output/WordDocument.docx", FileFormat.Docx2019)

Output

P.S. The red evaluation message can be eliminated by applying a trial license. Feel free to request one from the vendor via sales@e-iceblue.com.

Add Images to a Word Document in Python

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Add a seciton
section = document.AddSection()

# Add a paragraph
paragraph = section.AddParagraph()

# Add an image to the specified paragraph
picture = paragraph.AppendPicture("C:\\Users\\Administrator\\Desktop\\mountain.jpg")

# Scale mage size
picture.Width = picture.Width*0.5
picture.Height = picture.Height*0.5

# Set text wrapping style
# picture.TextWrappingStyle = TextWrappingStyle.Square

# Save the result document
document.SaveToFile("InsertImage.docx", FileFormat.Docx)
document.Close()

Output

Add Textboxes to a Word Document in Python

from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Add a section
section = document.AddSection()

# Add a paragraph
paragraph = section.AddParagraph()

# Insert a textbox and set its wrapping style
textBox = paragraph.AppendTextBox(250, 80)

# Set the position of the textbox
textBox.Format.HorizontalOrigin = HorizontalOrigin.LeftMarginArea
textBox.Format.HorizontalPosition = 50
textBox.Format.VerticalOrigin = VerticalOrigin.Page
textBox.Format.VerticalPosition = 150

# Set the border style and fill color of the textbox
textBox.Format.LineColor = Color.get_DarkBlue()
textBox.Format.FillColor = Color.get_LightGray()

# Add a paragraph to textbox
para = textBox.Body.AddParagraph();

# Set alignment for the paragraph
para.Format.HorizontalAlignment = HorizontalAlignment.Left

# Insert text to textbox as the second paragraph
textRange = para.AppendText("This textbox contains additional information related to the topic of this document.")

# Set the font of the text
textRange.CharacterFormat.FontName = "Times New Roman"
textRange.CharacterFormat.FontSize = 18
textRange.CharacterFormat.Italic = True

# Set text wrapping style
# textBox.Format.TextWrappingStyle = TextWrappingStyle.Square

# Save the result document
document.SaveToFile("AddTextBox.docx", FileFormat.Docx)

Output

Create Tables in a Word Document in Python

from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Add a table
table = section.Tables.Add()

# Set the border of table
table.TableFormat.Borders.BorderType = BorderStyle.Single
table.TableFormat.Borders.LineWidth = 1
table.TableFormat.Borders.Color = Color.get_Black()

# Add a row
row = table.AddRow(False, 3)
row.Height = 20.0
cell = row.Cells[0]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = cell.AddParagraph()
paragraph.AppendText("First Name")
cell = row.Cells[1]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = cell.AddParagraph()
paragraph.AppendText("Last Name")
cell = row.Cells[2]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = cell.AddParagraph()
paragraph.AppendText("Age")

# Add another row
row = table.AddRow(False, 3)
row.Height = 20.0
cell = row.Cells[0]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = cell.AddParagraph()
paragraph.AppendText("Nancy")
cell = row.Cells[1]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = cell.AddParagraph()
paragraph.AppendText("Jones")
cell = row.Cells[2]
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = cell.AddParagraph()
paragraph.AppendText("25")

# Save the document
doc.SaveToFile("CreateTable.docx", FileFormat.Docx2013)
doc.Close()

Output

Create Lists in a Word Document in Python

from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Add a section
section = doc.AddSection()

# Create a numbered list style
listStyle = ListStyle(doc, ListType.Numbered)
listStyle.Name = "numberedList"
listStyle.Levels[0].PatternType = ListPatternType.DecimalEnclosedParen
listStyle.Levels[0].TextPosition = 20;
doc.ListStyles.Add(listStyle)

# Add a paragraph
paragraph = section.AddParagraph()
paragraph.AppendText("Things to do today:")
paragraph.Format.AfterSpacing = 5.0

# Add a paragraph and apply the numbered list style to it
paragraph = section.AddParagraph()
paragraph.AppendText("Feed cat")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

# Add the other two paragraphs and apply the numbered list style to them
paragraph = section.AddParagraph()
paragraph.AppendText("Wash car")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()
paragraph.AppendText("Shopping")
paragraph.ListFormat.ApplyStyle("numberedList")
paragraph.ListFormat.ListLevelNumber = 0

# Save the document to file
doc.SaveToFile("CreateList.docx", FileFormat.Docx)

Output

Load a Word Document in Python

from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load an existing Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Edit the document

# Save to file
doc.SaveToFile("output.docx", FileFormat.Docx2019)

See Also

Convert Word to Images in Python

Convert Word to PDF in Python

Find and Replace Text in Word in Python

--

--

Alexander Stock

I'm Alexander Stock, a software development consultant and blogger with 10+ years' experience. Specializing in office document tools and knowledge introduction.