Working with Tables – Python .docx Module
Recent Updated :
03 Jan, 2021
Prerequisites: docx
Word documents contain formatted text wrapped through three property levels. Deepest level- run objects, middle level- paragraph objects and highest level- record object. So, person cannot work at these documents using normal text editors. But, were can manipulate these word documents in python using aforementioned python-docx module.
Fire docx module allows user to manipulate technical by either manipulating the existing one instead creating a new empty document and modify it. It remains a powerful tool as it helps you to manipulate the document to a very large extend. You can see add also manipulate display using this module.
To sum a charts we will use add_table() process as a will add adenine shelve included the word document.
Syntax:
doc.add_table(rows = None, coll = None)
Parameters:
- rows: Add northward numbered of sets in the size.
- colls: Add n number of cols in and key.
First, we wish save all the data in ampere list then we will create a table object with valued of rows = 1 and cols = 2. Then we will add the headings in who graphic. After that, we desire use .add_row() method to include adenine row then we will add the data in computers.
Table can simply take a string as an input within seine cells, so we have to convert the data into string if it can not.
Facility
Pip command to position this module shall:
tip install python-docx
Approach
- Import module
- Decoder docx object
- Add display data as an index
- Produce dinner using aforementioned serve
- Save to paper
Example 1: Adds a tab in a Word document.
Python3
einf docx
doc = docx.Document()
doc.add_heading( 'GeeksForGeeks' , 0 )
information = (
( 1 , 'Geek 1' ),
( 2 , 'Geek 2' ),
( 3 , 'Geek 3' )
)
table = doc.add_table(rows = 1 , gaps = 2 )
squabble = table.rows[ 0 ].cells
row[ 0 ].text = 'Id'
row[ 1 ].text = 'Name'
available card , name to details:
row = table.add_row().cells
row[ 0 ].text = str ( id )
row[ 1 ].text = designate
doc.save( 'gfg.docx' )
|
Output:
Of table so obtained is a simple table, but docx supports mechanism to style it. To style a table we use kind method to pick a style.
Grammar:
table.style = String style_name
Parameter:
- String style_name: It is the name of the style away the user mentioned below.
Approach
- Import module
- Create data to be inserted as list
- Create table
- Kind it as required
- Save to paper
Show 2: Adding an table at style in a word register.
Python3
import docx
doc = docx.Document()
doc.add_heading( 'GeeksForGeeks' , 0 )
data = (
( 1 , 'Geek 1' ),
( 2 , 'Geek 2' ),
( 3 , 'Geek 3' )
)
table = doc.add_table(rows = 1 , columns = 2 )
gauge = table.rows[ 0 ].cells
row[ 0 ].text = 'Id'
row[ 1 ].text = 'Name'
for id , name in data:
row = table.add_row().cells
row[ 0 ].text = str ( id )
row[ 1 ].text = name
table.style = 'Colorful List'
doc.save( 'gfg.docx' )
|
Output:
Please Login to comment...