Search code examples
pythonpython-docx

How to develop so that the fields below indicated are transformed into an MS WORD file, in an organized manner?


Fields:

A. Process number (with mask and 15 characters)

B. Stick Name (must be selection button and list with 3 options)

C. Part Name (must be text field of free filling)

 

 


Solution

  • If you do not already have python-docx installed, run the following pip command to install it:

    pip install python-docx
    

    Create a new python file and import docx

    import docx
    

    You can now do something of the following:

    MyDocument = docx.Document # Tells python the file extension to write to
    MyDocument.add_heading("This is a heading.", 0) # Makes a heading. Replace '0' with 1 or 2 to make it smaller
    MyDocument.add_paragraph("Hey, I'm a paragraph!") # Makes a paragraph
    MyDocument.save("C:/WordDocumentTest.docx") # Saves the document to its respective name, replace C:/ with a directory path
    

    This creates a paragraph under the .docx file extension, adds a sample paragraph, a heading, and saves it to the given name. You can add as many paragraphs as you want as long as it is given a handle, a paragraph to add, and a saving path.

    You can also create a run to put a section under a given paragraph by giving it a handle:

    secondParagraph = MyDocument.add_paragraph("I am the second paragraph!")
    secondParagraph.add_run("This is a run added as a section of the second paragraph")
    

    Here's my best answer to how to achieve what you want:

    from docx import Document
    from docx.shared import Inches
    
    MyDocument = docx.Document # Tells python the file extension to write to
    
    MyDocument.add_heading('Process Number,', level=1)
    MyDocument.add_paragraph('')
    MyDocument.add_heading('Stick Name', level=1)
    MyDocument.add_paragraph('List Option 1', style='List Number')
    MyDocument.add_paragraph('List Option 2', style='List Number')
    MyDocument.add_paragraph('List Option 3', style='List Number')
    
    records = ((3, 'Sample'),(7, 'Sample'))
    
    table = MyDocument.add_table(rows=1, cols=2)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Part Name'
    hdr_cells[1].text = ' '
    for name, id, desc in records:
        row_cells = table.add_row().cells
        row_cells[0].text = ''
        row_cells[1].text = ''
    
    MyDocument.save("C:/WordDocumentTest.docx") # Saves the document to its respective name, replace C:/ with a directory path
    

    If you need to look up something else, here's the documentation