Skip to main content
This example shows how to use the python-docx library to generate a datasheet report as a Word docx file. At a high level, the notebook goes through the following steps:
  1. Define the data to be included in the report
  2. Export the data
  3. Load the report template
  4. Add single-valued attributes to the report
  5. Add functional data to the report
  6. Save the report
The final step is optional and uses the docx2pdf library to convert the docx file to pdf. However, this step requires Microsoft Word to be installed on the computer running Python. If Word is not available, this step is skipped.

1. Define the data to be included in the report

First, define some constants that identify the record and attributes to be included in the report. The following cell identifies a record by Database Key, Table name, and Record History GUID, but an alternative technique could be used to identify a record, for example searching.
The next cells define the attributes to be included in each section of the report. Apart from the Datasheet Title attribute, these are dictionaries which map an attribute name to a label included in the report.
The GRAPHS dictionary maps functional attributes to a 4-tuple, where each element of the tuple refers to:
  1. The chart title
  2. The y-axis label
  3. The x-axis label
  4. Optional: For multiple-series plots, a 2-tuple of the Parameter name and the title of the legend in the report

2. Export the data

Export the data for all the required attributes for the ‘released’ version of the record.

3. Load the report template

The report template is created in Microsoft Word, and the ‘python-docx’ library is used to populate the template with data exported from Granta MI. Import the python-docx library and create a Document object using the docx.Document function. The function accepts an optional string as the relative path to a template file, which is used to create the Document object. In this example the relative path to the template file is "supporting_files/report_template.docx", and the Document object is stored in the report variable. docx.Document can also be called without arguments, which creates an empty Word document instead.
Info:As python-docx does not implement all the layout and style functionality in Microsoft Word, specifying a pre-defined template allows greater control over the layout of the document and more concise code overall.
A screenshot of the template is shown below: The Word template header section, showing a company logo and tables with placeholder values.

4. Add single-valued attributes to the report

This section covers adding single-valued and range attributes to the report. The report makes use of tables to present single-valued data, and so the general approach is as follows:
  1. Identify the table in the report template to be modified
  2. Format the attribute value as a string
  3. Add a new row to the table (if required)
  4. Add the value to the table and apply the appropriate style

Define a helper function to write a value to a cell

First, define a function that writes a value to a cell. Use the docx.table._Cell.iter_inner_content() to access the Paragraph object within the cell. The Paragraph.text and Paragraph.style properties are then used to modify the cell content and style respectively.

Write the datasheet title

The first table in the template contains identifying information about the material. The first row contains the title, and subsequent rows contain additional information about the material. The cell below does the following:
  1. Identifies the target table based on its location in the document.
  2. Identifies the target cell based on the row and column coordinates.
  3. Creates the title string based on the DATASHEET_TITLE_ATTRIBUTE attribute value and the record version number.
  4. Writes the value to the cell and applies the "Material Name" style as defined in the Word template document.
Modifying the report object does not provide any feedback. The report can be saved to disk as a docx file at any point by using the Document.save method. First, ensure the output directory exists. This directory will already exist if a notebook was run previously that saved a file to disk.
Next, save the report.
Open the report_header_only.docx file to see the report template populated with the DATASHEET_TITLE_ATTRIBUTE attribute value. A screenshot of the report with the title added is shown below: The header section of a Word document containing a populated title cell. The report will not be saved to disk again until the report is complete. If you want to see the effects of individual operations on the report, use the report.save method to save the report to disk at any point and open the file in Microsoft Word.

Write ‘Header’ attributes

The header attributes are written to additional rows in the first table. The general process for writing these attributes is the same as for the datasheet title attribute, but with the addition of iterating through multiple header attributes. For each header attribute, a new row is added to the table, and the attribute label and value are written to the new row. First, define a function that formats an attribute value to a suitable string format depending on the attribute type. The default format specifier :.3g uses a general format with at most 3 digits of precision.
Next, iterate through each header attribute and write the appropriately formatted value to the header table.

Write numeric attributes

Next, write the numeric attributes to the report. This step is similar to the header attributes above, except the value and unit are written to separate cells instead of being joined in a formatted string. Additionally, the table also contains two attributes per row, so some additional calculations are required to determine the row number.

5. Add functional data to the report

Plot functional attributes with seaborn and matplotlib, convert the plots to image files, and then embed these in the report. Note: This section assumes the user is familiar with seaborn and matplotlib. For more examples and guidance in using these libraries see the previous Data Analytics examples. First, define a helper function to convert a matplotlib plot to a png file.
Next, import seaborn and set the plot style.
Now, define a function to create a plot for a functional attribute with a specified title, axis labels, and optional constraint information.
Finally, use this function to create a plot image for each functional attribute and add it to the report. The plots are added to the end of the document, and automatically flow to a new page if the previous page is filled.
Previous cell output:

6. Save the report

The values and plots have been added to the Document object, but these changes have not yet been saved to disk. To save the file, use the Document.save method to create a docx file at the path specified.
A screenshot in Word is shown below (only the first page is shown): The first page of a populated Word document showing a company logo, populated data tables, and a plot of thermal
conductivity vs temperature.

Optional: Convert the file to PDF (not available in HTML documentation)

This final step uses the docx2pdf library to convert the docx file to pdf. The docx2pdf library requires a local installation of Word, and so is not supported on Linux. The output of this step is not available in the HTML documentation, but will be visible if you run this notebook in an environment with Word installed.
Display the PDF using the browser’s PDF engine.