Created
March 5, 2024 20:16
-
-
Save myersCody/d40c0a9c6b3361f86796ee7849a94840 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pip install prettytable | |
# pip install python-docx | |
from prettytable import PrettyTable | |
from docx import Document | |
from docx.shared import Pt | |
from docx.enum.table import WD_ALIGN_VERTICAL, WD_ALIGN_VERTICAL | |
def create_word_document(data): | |
if not data or not isinstance(data, list) or not isinstance(data[0], dict): | |
print("Invalid input. Expecting a list of dictionaries.") | |
return | |
document = Document() | |
# Add a table to the Word document | |
table = document.add_table(rows=1, cols=len(data[0])) | |
# Set column names as header row | |
header_row = table.rows[0].cells | |
for idx, key in enumerate(data[0].keys()): | |
header_row[idx].text = key | |
header_row[idx].paragraphs[0].runs[0].font.size = Pt(10) | |
header_row[idx].paragraphs[0].runs[0].bold = True | |
header_row[idx].vertical_alignment = WD_ALIGN_VERTICAL.CENTER | |
header_row[idx].paragraphs[0].runs[0].alignment = WD_ALIGN_VERTICAL.CENTER | |
# Add data rows to the table | |
for row_data in data: | |
row_cells = table.add_row().cells | |
for idx, value in enumerate(row_data.values()): | |
row_cells[idx].text = str(value) | |
# Save the Word document | |
document.save('output.docx') | |
# Example usage: | |
data_list = # Past in Trino Return | |
create_word_document(data_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment