Tuesday 14 January 2014

Generate a Word file using Python?

Generating a word document using python is not much difficult. We can easily generate by python. In my project i have generated PDF, DOCX and XLSX file with some python module.
So i am explaining how to create docx file in python, first you have to download python-docx module from here Download and download lxml module .


Now start install this python docx module in your system, type command on C prompt with python-docx path

C:\user\ashish\Desktop\
python-docx> python setup.py install


Keep create_docx.py file in python-docx module becoz all library is present in this folder.
now write below code for generating windows docx file
create_docx.py
 #!/usr/bin/env python
import os
from docx import *
x=str(os.path.abspath(os.path.join(os.path.expanduser('~'), 'Desktop')))

if __name__ == '__main__':
    relationships = relationshiplist()
    document = newdocument()
    body = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
    body.append(paragraph(" "))
    tbl_rows = [ ['Report'],
                 [' ', ' ']
               , ['Name', 'Ashish']
               , ['Email address', 'example@gmail.com']
               , ['mobile', '4569846569']
               , ['city', 'abc']
               ]
    body.append(table(tbl_rows))
    body.append(paragraph(" "))
    body.append(heading('Result', 2))
    body.append(paragraph(" "))
    points = ['C:\user\ashish\Desktop\python-docx\docx.py',
              'C:\user\ashish\Desktop\python-docx\abc.py',
              'welcome to python docx',
              'welcome to my python blog',
              ]        
    for point in points:
        body.append(paragraph(point, style='ListNumber'))
    relationships, picpara = picture(relationships, 'images1.png',
                                     'description')
    
    print 'Searching for something in a paragraph ...',
    if search(body, 'the awesomeness'):
        pass

    print 'Searching for something in a heading ...',
    if search(body, '200 lines'):
        pass
    body = replace(body, 'the awesomeness', 'the goshdarned awesomeness')
    print 'done.'
    body.append(paragraph(" "))
    body.append(heading('Thanks & Regards', 2))
    body.append(paragraph('Ashish'))
    body.append(paragraph('Email-example@gmail.com'))
    body.append(picpara)
    title    = 'Docx'
    subject  = 'create docx'
    creator  = 'ashish'
    keywords = ['ashish', 'Office Open XML', 'Word']
    coreprops = coreproperties(title=title, subject=subject, creator=creator,
                               keywords=keywords)
    appprops = appproperties()
    contenttypes = contenttypes()
    websettings = websettings()
    wordrelationships = wordrelationships(relationships)
    savedocx(document, coreprops, appprops, contenttypes, websettings,
             wordrelationships, x+'\create_doc.docx')


Thanks guys

4 comments:

  1. import os
    This statement is missing

    And, also the below are not defined:
    relationships = relationshiplist()
    document = newdocument()
    where are these function calls addressed.

    ReplyDelete
    Replies
    1. Thanks udhay for updating. I have updated missing things and for your reference, relationshiplist() and newdocument() function are available in python-docx module which i have imported in above code like that from docx import *.

      if any query please let me know?

      Delete
  2. I get the same problem - relationships = relationshiplist() document = newdocument() are not defined? according to help(docx) they don't exist-

    PACKAGE CONTENTS
    api
    blkcntnr
    compat
    dml (package)
    document
    enum (package)
    exceptions
    image (package)
    opc (package)
    oxml (package)
    package
    parts (package)
    section
    shape
    shared
    styles (package)
    table
    text (package)

    Any ideas how to make this work?

    Danny

    ReplyDelete
    Replies
    1. It's updated and now if u import "from docx import *" then relationshiplist() and newdocument() function will access through it

      Delete