DEV Community

Free Python Code
Free Python Code

Posted on

How to create or generate a WORD file using Python

Hi πŸ™‚πŸ–

In this post, I will show you how to create or generate a word file
using Python and a library called python_docx

Install python_docx

pip install python_docx 
Enter fullscreen mode Exit fullscreen mode
from docx import Document word_doc = Document() 
Enter fullscreen mode Exit fullscreen mode

Add heading

word_doc.add_heading('This is word file generated using Python', 1) 
Enter fullscreen mode Exit fullscreen mode

Add paragraph

word_doc.add_paragraph('This is text to test') 
Enter fullscreen mode Exit fullscreen mode

Add 5x5 table

table = word_doc.add_table(rows = 5, cols = 5) 
Enter fullscreen mode Exit fullscreen mode

Add data to table cells

table.cell(row_idx = 0, col_idx = 0).text = '123' table.cell(row_idx = 0, col_idx = 1).text = 'abc' 
Enter fullscreen mode Exit fullscreen mode

save the document

# save the word file word_doc.save('word_doc.docx') 
Enter fullscreen mode Exit fullscreen mode

Result

Image description

This I a simple example of how to generate a Word file in Python you can do more things with this library.

Top comments (0)