docx-mailmerge2


Namedocx-mailmerge2 JSON
Version 0.8.0 PyPI version JSON
download
home_pagehttp://github.com/iulica/docx-mailmerge
SummaryPerforms a Mail Merge on docx (Microsoft Office Word) files
upload_time2024-01-16 15:27:29
maintainer
docs_urlNone
authorIulian Ciorăscu
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            ===============
docx Mail Merge
===============

.. image:: https://badge.fury.io/py/docx-mailmerge2.png
    :alt: PyPI
    :target: https://pypi.python.org/pypi/docx-mailmerge2

Performs a Mail Merge on Office Open XML (docx) files. Can be used on any
system without having to install Microsoft Office Word. Supports Python 2.7,
3.3 and up.

Installation
============

Installation with ``pip``:
::

    $ pip install docx-mailmerge2


Usage
=====

Open the file.
::

    from mailmerge import MailMerge
    with MailMerge('input.docx',
            remove_empty_tables=False,
            auto_update_fields_on_open="no",
            keep_fields="none") as document:
        ...


List all merge fields.
::

    print(document.get_merge_fields())


Merge fields, supplied as kwargs.
::

    document.merge(field1='docx Mail Merge',
                   field2='Can be used for merging docx documents')

Merge table rows. In your template, add a MergeField to the row you would like
to designate as template. Supply the name of this MergeField as ``anchor``
parameter. The second parameter contains the rows with key-value pairs for
the MergeField replacements.

If the tables are empty and you want them removed, set remove_empty_tables=True
in constructor.
::

    document.merge_rows('col1',
                        [{'col1': 'Row 1, Column 1', 'col2': 'Row 1 Column 1'},
                         {'col1': 'Row 2, Column 1', 'col2': 'Row 2 Column 1'},
                         {'col1': 'Row 3, Column 1', 'col2': 'Row 3 Column 1'}])


Starting in version 0.2.0 you can also combine these two separate calls into a
single call to `merge`.
::

    document.merge(field1='docx Mail Merge',
                   col1=[
                       {'col1': 'A'},
                       {'col1': 'B'},
                   ])


Starting in version 0.2.0 there's also the feature for template merging.
This creates a copy of the template for each item in the list, does a merge,
and separates them by page or section breaks (see function documentation).
Starting in version 0.8.0 you can also use fields in the headers/footers/footnotes
with the merge_templates method.
::

    document.merge_templates([
        {'field1': "Foo", 'field2: "Copy #1"},
        {'field1': "Bar", 'field2: "Copy #2"},
    ], separator='page_break')


Starting in version 0.6.0 the fields formatting is respected when compatible.
Numeric, Text, Conditional and Date fields (0.6.2) are implemented.
For Date fields a compatible datetime, date or time objects must be provided.
If locale support is needed, make sure to call the setlocale before merging
::

    import locale
    locale.setlocale(locale.LC_TIME, '') # for system locale

    document.merge_templates([
        {'datefield': datetime.date('2022-04-15')},
    ], separator='page_break')

The {NEXT} fields are supported (0.6.3).

You can also use the merge fields inside other fields, for example to insert
pictures in the docx {INCLUDEPICTURE} or for conditional texts {IF}.
Microsoft Word is needed to update the values of those fields.
::

    { INCLUDEPICTURE "{ MERGEFIELD path }/{ MERGEFIELD image }" }
    { IF "{ MERGEFIELD reason }" <> "" "Reason: { MERGEFIELD reason }" }

Always enclose the fields with double quotes, as the MERGE fields will be first
filled in with data and then the other fields will be computed through Word.

If the fields are nested inside other fields, the outer fields need to be
updated in Word. This can be done by selecting everything (CTRL-a) and then
update the fields (F9). There is a way to force the Word to update fields
automatically when opening the document. docx-mailmerge can set this
setting when saving the document. You can configure this feature by using
the *auto_update_fields_on_open* parameter. The value *always* will set the
setting regardless if needed or not and the value *auto* will only set it
when necessary (when nested fields exist). The default value *no* will not
activate this setting.


Write document to file. This should be a new file, as ``ZipFile`` cannot modify
existing zip files.
::

    document.write('output.docx')

By default, all MERGEFIELD fields are replaced with their value. If a value is 
not given, it is replaced with an empty string.
If you want to keep the existing MERGEFIELD fields (with their current value)
you can specify the keep_fields="some" parameter in the constructor.
::

    from mailmerge import MailMerge
    with MailMerge('keep_unchanged_fields.docx',
            keep_fields="some") as document:
        ...

If you want to only update the value of the MERGEFIELD fields but keep the 
fields themselves, you can specify the keep_fields="all" parameter in the 
constructor. This way, you can change the document and update the fields again
later.
::

    from mailmerge import MailMerge
    with MailMerge('keep_all_fields.docx',
            keep_fields="all") as document:
        ...


See also the unit tests and this nice write-up `Populating MS Word Templates
with Python`_ on Practical Business Python for more information and examples.

Todo / Wish List
================

* Create single word documents for each row of data
* Implement SKIPIF and NEXTIF fields

Contributing
============

* Fork the repository on GitHub and start hacking
* Create / fix the unit tests
* Send a pull request with your changes

Unit tests
----------

In order to make sure that the library performs the way it was designed, unit
tests are used. When providing new features, or fixing bugs, there should be a
unit test that demonstrates it. Run the test suite::

    python -m unittest discover

Credits
=======

| This library was `originally`_ written by `Bouke Haarsma`_ and contributors.
| This repository is maintained by `Iulian Ciorăscu`_.

.. _Bouke Haarsma: https://twitter.com/BoukeHaarsma
.. _Populating MS Word Templates with Python: http://pbpython.com/python-word-template.html
.. _originally: https://github.com/Bouke/docx-mailmerge
.. _Iulian Ciorăscu: https://github.com/iulica/

            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/iulica/docx-mailmerge",
    "name": "docx-mailmerge2",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Iulian Cior\u0103scu",
    "author_email": "ciulian@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/68/c2/8abc8e1a93c82184ce770925750f97d12a44594c017ce3774805bce6bc28/docx-mailmerge2-0.8.0.tar.gz",
    "platform": null,
    "description": "===============\ndocx Mail Merge\n===============\n\n.. image:: https://badge.fury.io/py/docx-mailmerge2.png\n    :alt: PyPI\n    :target: https://pypi.python.org/pypi/docx-mailmerge2\n\nPerforms a Mail Merge on Office Open XML (docx) files. Can be used on any\nsystem without having to install Microsoft Office Word. Supports Python 2.7,\n3.3 and up.\n\nInstallation\n============\n\nInstallation with ``pip``:\n::\n\n    $ pip install docx-mailmerge2\n\n\nUsage\n=====\n\nOpen the file.\n::\n\n    from mailmerge import MailMerge\n    with MailMerge('input.docx',\n            remove_empty_tables=False,\n            auto_update_fields_on_open=\"no\",\n            keep_fields=\"none\") as document:\n        ...\n\n\nList all merge fields.\n::\n\n    print(document.get_merge_fields())\n\n\nMerge fields, supplied as kwargs.\n::\n\n    document.merge(field1='docx Mail Merge',\n                   field2='Can be used for merging docx documents')\n\nMerge table rows. In your template, add a MergeField to the row you would like\nto designate as template. Supply the name of this MergeField as ``anchor``\nparameter. The second parameter contains the rows with key-value pairs for\nthe MergeField replacements.\n\nIf the tables are empty and you want them removed, set remove_empty_tables=True\nin constructor.\n::\n\n    document.merge_rows('col1',\n                        [{'col1': 'Row 1, Column 1', 'col2': 'Row 1 Column 1'},\n                         {'col1': 'Row 2, Column 1', 'col2': 'Row 2 Column 1'},\n                         {'col1': 'Row 3, Column 1', 'col2': 'Row 3 Column 1'}])\n\n\nStarting in version 0.2.0 you can also combine these two separate calls into a\nsingle call to `merge`.\n::\n\n    document.merge(field1='docx Mail Merge',\n                   col1=[\n                       {'col1': 'A'},\n                       {'col1': 'B'},\n                   ])\n\n\nStarting in version 0.2.0 there's also the feature for template merging.\nThis creates a copy of the template for each item in the list, does a merge,\nand separates them by page or section breaks (see function documentation).\nStarting in version 0.8.0 you can also use fields in the headers/footers/footnotes\nwith the merge_templates method.\n::\n\n    document.merge_templates([\n        {'field1': \"Foo\", 'field2: \"Copy #1\"},\n        {'field1': \"Bar\", 'field2: \"Copy #2\"},\n    ], separator='page_break')\n\n\nStarting in version 0.6.0 the fields formatting is respected when compatible.\nNumeric, Text, Conditional and Date fields (0.6.2) are implemented.\nFor Date fields a compatible datetime, date or time objects must be provided.\nIf locale support is needed, make sure to call the setlocale before merging\n::\n\n    import locale\n    locale.setlocale(locale.LC_TIME, '') # for system locale\n\n    document.merge_templates([\n        {'datefield': datetime.date('2022-04-15')},\n    ], separator='page_break')\n\nThe {NEXT} fields are supported (0.6.3).\n\nYou can also use the merge fields inside other fields, for example to insert\npictures in the docx {INCLUDEPICTURE} or for conditional texts {IF}.\nMicrosoft Word is needed to update the values of those fields.\n::\n\n    { INCLUDEPICTURE \"{ MERGEFIELD path }/{ MERGEFIELD image }\" }\n    { IF \"{ MERGEFIELD reason }\" <> \"\" \"Reason: { MERGEFIELD reason }\" }\n\nAlways enclose the fields with double quotes, as the MERGE fields will be first\nfilled in with data and then the other fields will be computed through Word.\n\nIf the fields are nested inside other fields, the outer fields need to be\nupdated in Word. This can be done by selecting everything (CTRL-a) and then\nupdate the fields (F9). There is a way to force the Word to update fields\nautomatically when opening the document. docx-mailmerge can set this\nsetting when saving the document. You can configure this feature by using\nthe *auto_update_fields_on_open* parameter. The value *always* will set the\nsetting regardless if needed or not and the value *auto* will only set it\nwhen necessary (when nested fields exist). The default value *no* will not\nactivate this setting.\n\n\nWrite document to file. This should be a new file, as ``ZipFile`` cannot modify\nexisting zip files.\n::\n\n    document.write('output.docx')\n\nBy default, all MERGEFIELD fields are replaced with their value. If a value is \nnot given, it is replaced with an empty string.\nIf you want to keep the existing MERGEFIELD fields (with their current value)\nyou can specify the keep_fields=\"some\" parameter in the constructor.\n::\n\n    from mailmerge import MailMerge\n    with MailMerge('keep_unchanged_fields.docx',\n            keep_fields=\"some\") as document:\n        ...\n\nIf you want to only update the value of the MERGEFIELD fields but keep the \nfields themselves, you can specify the keep_fields=\"all\" parameter in the \nconstructor. This way, you can change the document and update the fields again\nlater.\n::\n\n    from mailmerge import MailMerge\n    with MailMerge('keep_all_fields.docx',\n            keep_fields=\"all\") as document:\n        ...\n\n\nSee also the unit tests and this nice write-up `Populating MS Word Templates\nwith Python`_ on Practical Business Python for more information and examples.\n\nTodo / Wish List\n================\n\n* Create single word documents for each row of data\n* Implement SKIPIF and NEXTIF fields\n\nContributing\n============\n\n* Fork the repository on GitHub and start hacking\n* Create / fix the unit tests\n* Send a pull request with your changes\n\nUnit tests\n----------\n\nIn order to make sure that the library performs the way it was designed, unit\ntests are used. When providing new features, or fixing bugs, there should be a\nunit test that demonstrates it. Run the test suite::\n\n    python -m unittest discover\n\nCredits\n=======\n\n| This library was `originally`_ written by `Bouke Haarsma`_ and contributors.\n| This repository is maintained by `Iulian Cior\u0103scu`_.\n\n.. _Bouke Haarsma: https://twitter.com/BoukeHaarsma\n.. _Populating MS Word Templates with Python: http://pbpython.com/python-word-template.html\n.. _originally: https://github.com/Bouke/docx-mailmerge\n.. _Iulian Cior\u0103scu: https://github.com/iulica/\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Performs a Mail Merge on docx (Microsoft Office Word) files",
    "version": "0.8.0",
    "project_urls": {
        "Homepage": "http://github.com/iulica/docx-mailmerge"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "943b95dad9aa88d9f494eebdfce757e1d131ca578eaddeae8e10a2fd25bea02b",
                "md5": "9b3ff8b5b3bab26bf3c3e2e77ef8a815",
                "sha256": "b8507909b294aee6c6d9b46420e332875b05b741c9df8d06b498ec51ee64f78d"
            },
            "downloads": -1,
            "filename": "docx_mailmerge2-0.8.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9b3ff8b5b3bab26bf3c3e2e77ef8a815",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 16465,
            "upload_time": "2024-01-16T15:27:27",
            "upload_time_iso_8601": "2024-01-16T15:27:27.451519Z",
            "url": "https://files.pythonhosted.org/packages/94/3b/95dad9aa88d9f494eebdfce757e1d131ca578eaddeae8e10a2fd25bea02b/docx_mailmerge2-0.8.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "68c28abc8e1a93c82184ce770925750f97d12a44594c017ce3774805bce6bc28",
                "md5": "f15f4cd1f1704638d0fdf4928291ea6c",
                "sha256": "4652c5055a565bbdf3606f2786ce900486d2fb7ec26f30a800b89a5969ac0097"
            },
            "downloads": -1,
            "filename": "docx-mailmerge2-0.8.0.tar.gz",
            "has_sig": false,
            "md5_digest": "f15f4cd1f1704638d0fdf4928291ea6c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 28863,
            "upload_time": "2024-01-16T15:27:29",
            "upload_time_iso_8601": "2024-01-16T15:27:29.031015Z",
            "url": "https://files.pythonhosted.org/packages/68/c2/8abc8e1a93c82184ce770925750f97d12a44594c017ce3774805bce6bc28/docx-mailmerge2-0.8.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-01-16 15:27:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "iulica",
    "github_project": "docx-mailmerge",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "docx-mailmerge2"
}
        
Elapsed time: 0.20212s