Here’s an example code in Python to write data to an Access Word document using the docx
library
import docx # Open the Word document doc = docx.Document('path/to/document.docx') # Define the data to be written data = [ ['Name', 'Age', 'Gender'], ['John', '25', 'Male'], ['Sarah', '30', 'Female'], ['David', '22', 'Male'] ] # Add a table to the document table = doc.add_table(rows=1, cols=3) table.style = 'Table Grid' # Add the header row to the table hdr_cells = table.rows[0].cells for i in range(3): hdr_cells[i].text = data[0][i] # Add the data rows to the table for row in data[1:]: row_cells = table.add_row().cells for i in range(3): row_cells[i].text = row[i] # Save the changes to the document doc.save('path/to/document.docx') print('Data has been written to the Word document successfully.')
This code opens a Word document using the Document()
method, defines a list of data to be written to the document, adds a table to the document using the add_table()
method, adds the header row to the table using the first row of the data list, and adds the data rows to the table using the remaining rows of the data list. Finally, it saves the changes to the document using the save()
method and prints a message to indicate that the data has been written successfully.