Python docx is a useful
module that can be used to put things into word. I have previously worked with
Oracle BI Publisher for many years and can say after a few months with
Python-Docx that in most ways I already prefer it.
Again, this is really
just a quick intro into python-docx as a starting point for a series of posts
on what you can actually do and how to do it.
Installing:
Pip or conda install
python-docx
Using Python-Docx
Well see some of the
real basics in the code below, however I am going to work up 2 a couple of projects.
The first creating a CV using SQL Server and python-docx and the second
creating a monthly management report using python-docx (and sql server).
The code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#### docx and pandas imports | |
from docx import Document | |
import pandas as pd | |
from docx.shared import RGBColor | |
from docx.enum.text import WD_ALIGN_PARAGRAPH | |
from docx.shared import Cm , Pt | |
# create new document | |
document = Document() | |
#set up font | |
font = document.styles['Normal'].font | |
font.name = 'Arial' | |
font.size = Pt(10) | |
# set up margins | |
sections = document.sections | |
for section in sections: | |
section.top_margin = Cm(1.25) | |
section.bottom_margin = Cm(1.25) | |
section.left_margin = Cm(1.75) | |
section.right_margin = Cm(1.75) | |
# Add some text | |
p = document.add_paragraph() | |
p.add_run('Hello World') | |
# Add a heading, level 2 | |
document.add_heading('Profile', level=2) | |
# Save document | |
document.save(r'Document.docx') |
No comments:
Post a Comment