Creating Word documents using the Python Docx package is very powerful and allows us to present our data and findings in an automated way.
Many times, we are working with data and want to output this data into a table.
Outputting data to a table in a Word Document in Python is not difficult, but making this process efficient and fast is the key to making our work as good as it can be.
Creating a Table in a Word Document using Python Docx Efficiently
Creating a table and filling the table with data in a Word document using Python Docx is easy.
To create a table, all we need to do is:
import docx doc = docx.Document() table = doc.add_table(rows=ROWS, cols=COLS) doc.save("output_file_path.docx")
When writing small tables to word, we can loop through the table and there will not be any performance problems.
Let’s say we are reading some data from an XLSX file and we want to output it in a table in a Word document.
If the data is small, we can easily output the table without problems.
import docx import pandas as pd data = pd.read_excel("some_data.xlsx") doc = docx.Document() table = doc.add_table(rows=data.shape, cols=data.shape) for i in range(df.shape): for j in range(df.shape): table.cell(i,j).text = str(df.values[i,j]) doc.save("output_file_path.docx")
But, the problem is that when you use “table.cell(i,j).text”, this updates the table in the Word document and is very slow.
The more efficient way is to do the following:
import docx import pandas as pd data = pd.read_excel("some_bigger_data.xlsx") doc = docx.Document() table = doc.add_table(rows=data.shape, cols=data.shape) table_cells = table._cells for i in range(data.shape): for j in range(data.shape): table_cells[j + i * data.shape].text = str(data.values[i][j]) doc.save("output_file_path.docx")
The key is to use table._cells to “pop” out the cells from the table. With this line, we limit the amount of calls to the table in the Word document. By updating the Word document only after you have filled the table, you will improve the efficiency and speed of your program.
Hopefully this has been helpful in helping you write a table from a dataframe to Word document faster, and with this code, you can make your processes more efficient and take less time.
Let me know if you have any questions, and thank you for reading.