python-docx | Create and modify Word documents with Python

 by   python-openxml Python Version: 1.1.2 License: MIT

kandi X-RAY | python-docx Summary

kandi X-RAY | python-docx Summary

python-docx is a Python library. python-docx has no bugs, it has build file available, it has a Permissive License and it has high support. However python-docx has 1 vulnerabilities. You can install using 'pip install python-docx' or download it from GitHub, PyPI.

Create and modify Word documents with Python
Support
    Quality
      Security
        License
          Reuse

            kandi-support Support

              python-docx has a highly active ecosystem.
              It has 3649 star(s) with 966 fork(s). There are 150 watchers for this library.
              There were 2 major release(s) in the last 12 months.
              There are 518 open issues and 522 have been closed. On average issues are closed in 66 days. There are 102 open pull requests and 0 closed requests.
              It has a positive sentiment in the developer community.
              The latest version of python-docx is 1.1.2

            kandi-Quality Quality

              python-docx has 0 bugs and 0 code smells.

            kandi-Security Security

              python-docx has 1 vulnerability issues reported (0 critical, 1 high, 0 medium, 0 low).
              python-docx code analysis shows 0 unresolved vulnerabilities.
              There are 0 security hotspots that need review.

            kandi-License License

              python-docx is licensed under the MIT License. This license is Permissive.
              Permissive licenses have the least restrictions, and you can use them in most projects.

            kandi-Reuse Reuse

              python-docx releases are not available. You will need to build from source code and install.
              Deployable package is available in PyPI.
              Build file is available. You can build the component from source.
              python-docx saves you 58034 person hours of effort in developing the same functionality from scratch.
              It has 66430 lines of code, 3249 functions and 251 files.
              It has medium code complexity. Code complexity directly impacts maintainability of the code.

            Top functions reviewed by kandi - BETA

            kandi has reviewed python-docx and discovered the below as its top functions. This is intended to give you an instant insight into python-docx implemented functionality, and help decide if they suit your requirements.
            • Throw exception if the rectangle is not rectangular
            • Converts an W3CDCD formatted string to a datetime object .
            • Get scaled dimensions .
            • Walk through the physic part .
            • Add a get or change to a group element .
            • Calculate the height for a specific resolution .
            • Returns the hex color .
            • Compares the core properties of a context .
            • Return the XML representation of the pic .
            • Assigns new values to the context .
            Get all kandi verified functions for this library.

            python-docx Key Features

            No Key Features are available at this moment for python-docx.

            python-docx Examples and Code Snippets

            why the loop is not printing the correct statements?
            Pythondot img1Lines of Code : 4dot img1License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            if norm_color == {None}:
            
            if not norm_misc_color: # an empty set is falsey
            
            How to change style of hyperlinks in existing document, especially font size and name
            Pythondot img2Lines of Code : 29dot img2License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            from docx.oxml.shared import qn
            
            def getParagraphRuns(paragraph):
                def _get(node, parent):
                    for child in node:
                        if child.tag == qn('w:r'):
                            yield Run(child, parent)
                        if
            Iterate over pathlib paths and python-docx: zipfile.BadZipFile
            Pythondot img3Lines of Code : 9dot img3License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            document = Document()
            document.save(files[1])
            
            document = Document(files[1])
            document.save(files[1])
            
            with open(files[1], 'rb') as f:
                document = Document(f)
            
            Generate non-duplicate list in python
            Pythondot img4Lines of Code : 11dot img4License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            def get_hyperlinks(docx__document):    
                hyperlinks, returned_links = list(), set()
                for counter, element in enumerate(docx__document.elements):
                    if isinstance(element, Paragraph) and not element.is_heading:
                        hyperl
            Python chunk list from one element to another
            Pythondot img5Lines of Code : 17dot img5License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            from itertools import groupby
            
            groups, next_group = [], []
            
            for k, group in groupby(document.paragraphs, lambda x: x.style.name == 'Heading 2'):
                # If the predicate is True and next_group is populated,
                # we create a new chunk
                if
            How do I Add Custom XML to An Element Using Python-Docx?
            Pythondot img6Lines of Code : 23dot img6License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            def qn(tag):
                """
                Stands for "qualified name", a utility function to turn a namespace
                prefixed tag name into a Clark-notation qualified tag name for lxml. For
                example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld
            How do I Add Custom XML to An Element Using Python-Docx?
            Pythondot img7Lines of Code : 10dot img7License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            def set_text_wrap_around_table(table):
                w_namespace = '{' + nsmap['w'] + '}'
                tblPrElement = Element('{w}tblpPr'.format(w=w_namespace),
                                       {'{w}leftFromText'.format(w=w_namespace): '180',
                                 
            pyqt5 qtextdocument align from right to left and export to pdf?
            Pythondot img8Lines of Code : 6dot img8License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            for row in range(table.rows()):
                        for column in range(table.columns()- 1, -1, -1):
                            index = model.index(row, column)
                            cursor.insertText(str(model.data(index)))
                            cursor.movePosition(QtG
            How do you insert a lxml tag with namespace while skipping xmlns?
            Pythondot img9Lines of Code : 4dot img9License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            from docx.oxml import OxmlElement
            
            r = OxmlElement("m:r")
            
            Access Run nested elements - Python Docx
            Pythondot img10Lines of Code : 3dot img10License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            r = run._r
            fldChars = r.xpath("./w:fldChar")
            

            Community Discussions

            QUESTION

            why the loop is not printing the correct statements?
            Asked 2022-Apr-09 at 02:15

            I am working on some code to check the colour of the font used in a Word document. I am using python 3.10.4 and the python-docx library (version 0.8.1.1) on PyCharm (Community Edition 2021.3.3).

            The text being checked here is formatted with the 'Normal' style. The only accepted colour is the Automatic black, which python-docx prints as None as it a default colour.

            When I execute my code (as shown below) the only statement that is printed is: "Normal text font colour is black." This was the result when I used a document with text in both black and red. So in this instance it should have printed, "Normal text contains unrecognised font color(s):", along with the contents of norm_misc_color.

            I believe this error in the code may be due to they way None is being used in last block of loops. The sets norm_color and norm_misc_color print the correct values as required. I would like to know how I can print the correct statement under the specific conditions. Any form of help would be appreciated. If there are any questions regarding the code please ask.

            ...

            ANSWER

            Answered 2022-Apr-09 at 02:15

            Your if condition at the end of your code is only checking that there is some text in the file that uses the default font color. It doesn't exclude files that contain more than one text color, as long as the default color is included somewhere.

            There are a few different ways you can change your if/elif checks to handle the situation they way your comments say you want to. You could test that norm_color is a set that contains only None and nothing else with:

            Source https://stackoverflow.com/questions/71794365

            QUESTION

            How to output the correct statement in a loop using python
            Asked 2022-Apr-04 at 22:04

            I am currently working on some python (version 3.10.4) code on PyCharm (Community Edition 2021.3.3) using the python-docx library (version 0.8.1.1), that allows to determine if text (in a Word document) formatted in the 'Normal' style contains a specific font (Times New Roman or Times New Roman and Cambria Math). When I execute the code the statements printed are not those desired.

            What I mean here is that if all text (in the 'Normal' style) are in Times New Roman it should print, "Body text is in Times New Roman", while if text contains both Times New Roman and Cambria Math it should print, "Body text is Times New Roman and Cambria Math" and if text is neither all Times New Roman nor a combo of Times New Roman and Cambria Math, it should print, "Unrecognised body text font".

            When I execute the code (as shown below) it prints a combination of 'Body text is in Times New Roman' and 'Unrecognised body text font' (both printed the amount of times such occurrences are present in the document). The Word document contains the following fonts: Times New Roman, Cambria Math and Arial (used only for testing purposes). So it should print "Unrecognised body text font" (as all text are not Times New Roman nor a combo of Times New Roman and Cambria Math).

            ...

            ANSWER

            Answered 2022-Apr-04 at 02:31

            If I understood the question correctly, I think the easiest way to edit your current implementation would be to keep track of what fonts you identify. You could save the identified fonts in a set and check what's found after the loop. So something like this:

            Source https://stackoverflow.com/questions/71731308

            QUESTION

            How to change style of hyperlinks in existing document, especially font size and name
            Asked 2022-Mar-17 at 21:19

            I would like to stick with python-docx library. But if there are other ways would love to hear them.

            Currently i'm using this snippet for changing style in document, but links are no affected. Should I recreate them?

            ...

            ANSWER

            Answered 2022-Mar-17 at 21:19
            from docx.oxml.shared import qn
            

            Source https://stackoverflow.com/questions/71440523

            QUESTION

            Iterate over pathlib paths and python-docx: zipfile.BadZipFile
            Asked 2022-Mar-11 at 01:20

            My python skills are a bit rusty since I recently primarily used Rstats. However I ran into the following problem, my goal is that I want to recursively iterate over all .docx files in a directory and change some of the core attributes with the python-docx package.

            For the loop, I first created a list with pathlib and glob

            ...

            ANSWER

            Answered 2022-Mar-11 at 01:15

            You are not doing wrong, since documents are empty you are getting this error. If you open those files type something, you will not get any error. But According to https://python-docx.readthedocs.io/en/latest/user/documents.html

            You can open word documents with different codes.

            First:

            Source https://stackoverflow.com/questions/71432162

            QUESTION

            Generate non-duplicate list in python
            Asked 2022-Mar-06 at 11:02

            I am trying to generate a list that contains anchor names in w:hyperlink elements by looping over all document's elements using the python-docx library, with this code:

            ...

            ANSWER

            Answered 2022-Mar-04 at 09:44

            return list(dict.fromkeys(youdublicated_list))

            Source https://stackoverflow.com/questions/71349377

            QUESTION

            python-docx adding bold and non-bold strings to same cell in table
            Asked 2022-Feb-26 at 21:23

            I'm using python-docx to create a document with a table I want to populate from textual data. My text looks like this:

            ...

            ANSWER

            Answered 2022-Feb-26 at 21:23

            You need to add run in the cell's paragraph. This way you can control the specific text you wish to bold

            Full example:

            Source https://stackoverflow.com/questions/71150313

            QUESTION

            Output .docx document using repository in palantir foundry
            Asked 2022-Feb-12 at 22:29

            Since the foundry documentation is rather patchy and didn't really provide an answer: Is it somehow possible to use a foundry code repository (python-docx library is available and used) and a df as input to produce word documents (.docx) as output? I thought that maybe using a composition of the transform input/output and py-docx document.save() functionality may work but I couldn't come up with a proper solution.

            ...

            ANSWER

            Answered 2022-Feb-12 at 22:29

            Your best bet is to use spark to distribute the file generation over executors. This transformation generates a word doc for each row and stores in a dataset container, which is recommended over using Compass (Foundry's folder system). Browse to the dataset to download the underlying files

            Source https://stackoverflow.com/questions/71079515

            QUESTION

            Python chunk list from one element to another
            Asked 2022-Feb-11 at 14:46

            I've got the following code:

            ...

            ANSWER

            Answered 2022-Feb-11 at 14:46

            You could use an itertools.groupby to accomplish this:

            Source https://stackoverflow.com/questions/71081853

            QUESTION

            How do I Add Custom XML to An Element Using Python-Docx?
            Asked 2022-Feb-10 at 05:02

            I've been trying to get text wrapping for my table which isn't implemented in python-docx.

            So far so good, I've isolated that MS Word adds as a child to the table properties element so I just need to inject that into my table in python-docx.

            I got real close. Because I was able to find the element class in the library to add a child to. However my problem lays in the w: namespace because it won't let me construct an Element tag with the ':' character in it. I tried two methods, both failed.

            tblPrElement = Element('w:tblpPr ', {'w:leftFromText': '180', 'w:rightFromText': '180', 'w:vertAnchor': 'text', 'w:tblpY': '1' })

            tblPrElement = parse_xml('')

            If I try it omitting the w: ...

            ...

            ANSWER

            Answered 2022-Feb-05 at 00:02

            If you want to use lxml to append the XML using an Element you will have to provide python-docx's namespace map (docx.oxml.nsmap) when creating the Element.

            The syntax for inserting a namespace in a tag name is {namespacevalue}tagname.

            For example, <{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tblpPr/>

            Here is a method you can use to set the table to text wrapping using your XML.

            Source https://stackoverflow.com/questions/70992530

            QUESTION

            Running into an error when trying to pip install python-docx
            Asked 2022-Feb-06 at 17:04

            I just did a fresh install of windows to clean up my computer, moved everything over to my D drive and installed Python through Windows Store (somehow it defaulted to my C drive, so I left it there because Pycharm was getting confused about its location), now I'm trying to pip install the python-docx module for the first time and I'm stuck. I have a recent version of Microsoft C++ Visual Build Tools installed. Excuse me for any irrelevant information I provided, just wishing to be thorough. Here's what's returning in command:

            ...

            ANSWER

            Answered 2022-Feb-06 at 17:04

            One of the dependencies for python-docx is lxml. The latest stable version of lxml is 4.6.3, released on March 21, 2021. On PyPI there is no lxml wheel for 3.10, yet. So it try to compile from source and for that Microsoft Visual C++ 14.0 or greater is required, as stated in the error.

            However you can manually install lxml, before install python-docx. Download and install unofficial binary from Gohlke Alternatively you can use pipwin to install it from Gohlke. Note there may still be problems with dependencies for lxml.

            Of course, you can also downgrade to python3.9.

            EDIT: As of 14 Dec 2021 the latest lxml version 4.7.1 supports python 3.10

            Source https://stackoverflow.com/questions/69687604

            Community Discussions, Code Snippets contain sources that include Stack Exchange Network

            Vulnerabilities

            Install python-docx

            You can install using 'pip install python-docx' or download it from GitHub, PyPI.
            You can use python-docx like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

            Support

            For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
            Find more information at:

            Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

            Find more libraries
            Install
          • PyPI

            pip install python-docx

          • CLONE
          • HTTPS

            https://github.com/python-openxml/python-docx.git

          • CLI

            gh repo clone python-openxml/python-docx

          • sshUrl

            git@github.com:python-openxml/python-docx.git

          • Stay Updated

            Subscribe to our newsletter for trending solutions and developer bootcamps

            Agree to Sign up and Terms & Conditions

            Share this Page

            share link