# Process each row in the Excel file
for index, row in df.iterrows():
# Load the template for each row
doc = Document(template_file)
# Extract data from the Excel row and handle NaN values
client_name = row.get('Client Name ', '') if pd.notna(row.get('Client Name ', '')) else ''
matter_overview = row.get('Matter/Case Overview', '') if pd.notna(row.get('Matter/Case Overview', '')) else ''
description = row.get('Description (in 500 words)', '') if pd.notna(row.get('Description (in 500 words)', '')) else ''
value = row.get('Value ', '') if pd.notna(row.get('Value ', '')) else ''
lead_partners = row.get('Lead partners', '') if pd.notna(row.get('Lead partners', '')) else ''
Team_partners = row.get('Team Members', '') if pd.notna(row.get('Team Members', '')) else ''
Dates = row.get('Current Status (ongoing / completed )', '') if pd.notna(row.get('Current Status (ongoing / completed )', '')) else ''
publishable = row.get('Confidential / Publishable', '') if pd.notna(row.get('Confidential / Publishable', '')) else ''
if len(doc.tables) > 0:
table = doc.tables[0]
# Client Name
table.cell(3, 0).text = client_name
# Matter description
matter_text = f"{matter_overview}\n\n{description}"
table.cell(5, 0).text = matter_text
# Deal value
table.cell(6, 1).text = str(value)
# Lead partner(s)
table.cell(9, 0).text = lead_partners
table.cell(13, 0).text = Team_partners
table.cell(16, 3).text = Dates
# Create a temporary filename
clean_client_name = ''.join(c for c in client_name if c.isalnum() or c in [' ', '_']).replace(' ', '_')
temp_filename = os.path.join(temp_dir, f"{clean_client_name}.docx")
# Save the populated document to the temporary directory
doc.save(temp_filename)
print(f"Created temporary document: {temp_filename}")
Assistant
User
Assistant
User
Assistant
def combine_documents(temp_dir, output_file):
code
combined_doc = Document()
for filename in os.listdir(temp_dir):
if filename.endswith('.docx'):
file_path = os.path.join(temp_dir, filename)
sub_doc = Document(file_path)
# Loop through each element in the sub-doc and copy it to the combined document
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_file)
print(f"Combined document created: {output_file}")
if name == "main":
main() in this just like above add steamlit intetrace for excel only and pass tempalte throughcode itslef
To create a Streamlit interface for your existing code, you will need to add a file uploader for the Excel file and modify the template_file to be included as a hardcoded variable in your code. Below is a basic implementation that integrates Streamlit into your existing script.
The Streamlit interface will allow the user to upload an Excel file.
The template file will be included directly in the code.
Once the file is uploaded and the user submits, the document generation will happen as before.
Here's how you can modify your code:
python
import os
import pandas as pd
from docx import Document
import streamlit as st
def populate_docx_template(excel_file, template_file, temp_dir):
# Load Excel data
df = pd.read_excel(excel_file)
# Process each row in the Excel file
for index, row in df.iterrows():
# Load the template for each row
doc = Document(template_file)
# Extract data from the Excel row and handle NaN values
client_name = row.get('Client Name ', '') if pd.notna(row.get('Client Name ', '')) else ''
matter_overview = row.get('Matter/Case Overview', '') if pd.notna(row.get('Matter/Case Overview', '')) else ''
description = row.get('Description (in 500 words)', '') if pd.notna(row.get('Description (in 500 words)', '')) else ''
value = row.get('Value ', '') if pd.notna(row.get('Value ', '')) else ''
lead_partners = row.get('Lead partners', '') if pd.notna(row.get('Lead partners', '')) else ''
Team_partners = row.get('Team Members', '') if pd.notna(row.get('Team Members', '')) else ''
Dates = row.get('Current Status (ongoing / completed )', '') if pd.notna(row.get('Current Status (ongoing / completed )', '')) else ''
publishable = row.get('Confidential / Publishable', '') if pd.notna(row.get('Confidential / Publishable', '')) else ''
if len(doc.tables) > 0:
table = doc.tables[0]
# Client Name
table.cell(3, 0).text = client_name
# Matter description
matter_text = f"{matter_overview}\n\n{description}"
table.cell(5, 0).text = matter_text
# Deal value
table.cell(6, 1).text = str(value)
# Lead partner(s)
table.cell(9, 0).text = lead_partners
table.cell(13, 0).text = Team_partners
table.cell(16, 3).text = Dates
# Create a temporary filename
clean_client_name = ''.join(c for c in client_name if c.isalnum() or c in [' ', '_']).replace(' ', '_')
temp_filename = os.path.join(temp_dir, f"{clean_client_name}.docx")
# Save the populated document to the temporary directory
doc.save(temp_filename)
print(f"Created temporary document: {temp_filename}")
def combine_documents(temp_dir, output_file):
combined_doc = Document()
for filename in os.listdir(temp_dir):
if filename.endswith('.docx'):
file_path = os.path.join(temp_dir, filename)
sub_doc = Document(file_path)
# Loop through each element in the sub-doc and copy it to the combined document
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_file)
print(f"Combined document created: {output_file}")
def main():
st.title("Document Generator")
excel_file = st.file_uploader("Upload Excel File", type=["xlsx"])
if excel_file is not None:
temp_dir = 'temp_docs'
output_file = 'combined_output.docx'
template_file = r'c:\Users\Administrator\Desktop\legal500.docx'
os.makedirs(temp_dir, exist_ok=True)
if st.button("Generate Documents"):
try:
populate_docx_template(excel_file, template_file, temp_dir)
combine_documents(temp_dir, output_file)
st.success(f"Combined document created: {output_file}")
except Exception as e:
st.error(f"Error: {e}")
if __name__ == "__main__":
main()
Changes Made
Import Streamlit (import streamlit as st).
Added st.file_uploader() for users to upload an Excel file.
Added buttons using st.button() to trigger the document generation upon user interaction.
Adjusted the main() function to manage Streamlit's behavior instead of a traditional script run.
Running This Code
To run this code, ensure you have Streamlit installed in your Python environment. You can install it using:
bash
pip install streamlit
You can then run your Streamlit app with:
bash
streamlit run your_script_name.py
Replace your_script_name.py with the actual filename of your script. This will start a local server, and you can interact with the web interface in your browser to upload the Excel file and process it as needed.
import pandas as pd
from docx import Document
from docx.shared import RGBColor, Pt
import os
from docx.oxml.ns import qn
import streamlit as st
Hardcoded paths for the Word templates
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Iflr_Yes.docx" # Template for Yes rows
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Iflr_No.docx" # Template for No rows
# Variables to keep track of counts of documents
confidential_count = 0
non_confidential_count = 0
# Create directories for temporary files if they don't exist
temp_dir = os.path.join(os.path.dirname(output_path), "temp")
os.makedirs(temp_dir, exist_ok=True)
yes_files = []
no_files = []
# Iterate through each row of the DataFrame
for i, row in df.iterrows():
# Determine which document to use based on the Confidential/Publishable column
confidential_val = str(row.get('Confidential / Publishable ', '')).strip()
if confidential_val.lower() == 'yes' and confidential_count < 10:
confidential_count += 1
# Create a new document from the template for each row
doc = Document(TEMPLATE_PATH_YES)
if doc.tables:
table = doc.tables[0] # Use the first table in the template
fill_table_with_data(row, table, True, confidential_count)
# Save as temporary file
temp_file = os.path.join(temp_dir, f"yes_{i}.docx")
doc.save(temp_file)
yes_files.append(temp_file)
print(f"Created 'Yes' document for row {confidential_count}")
else:
print(f"Warning: No tables found in the 'Yes' template.")
elif confidential_val.lower() == 'no' and non_confidential_count < 10:
non_confidential_count += 1
# Create a new document from the template for each row
doc = Document(TEMPLATE_PATH_NO)
if doc.tables:
table = doc.tables[0] # Use the first table in the template
fill_table_with_data(row, table, False, non_confidential_count)
# Save as temporary file
temp_file = os.path.join(temp_dir, f"no_{i}.docx")
doc.save(temp_file)
no_files.append(temp_file)
print(f"Created 'No' document for row {non_confidential_count}")
else:
print(f"Warning: No tables found in the 'No' template.")
else:
print(f"Warning: Maximum limit reached for {'confidential' if confidential_val.lower() == 'yes' else 'non-confidential'} documents or unexpected value in the 'Confidential / Publishable ' column: {confidential_val}.")
# Combine all documents: 'No' files followed by 'Yes' files
combine_word_documents(no_files + yes_files, output_path)
print(f"All documents combined successfully to {output_path}!")
# Clean up temporary files
for file in no_files + yes_files:
try:
os.remove(file)
except Exception as e:
print(f"Warning: Could not delete temporary file {file}: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def fill_table_with_data(row, table, is_confidential, count):
try:
if len(table.rows) >= 25: # Make sure the table has enough rows
# Fill cell 0 with the format "Example x/10"
fill_cell(table.cell(0, 0), f"Example {min(count, 10)}/10", is_confidential, style='special')
fill_cell(table.cell(2, 0), 'Y' if is_confidential else 'N', is_confidential) # Cell 2 filled with 'Y' or 'N'
fill_cell(table.cell(6, 0), str(row['Client Name ']), is_confidential) # Client Name
fill_cell(table.cell(14, 0), str(row['Value ']), is_confidential) # Matter/Case Overview
fill_cell(table.cell(20, 0), str(row['Lead partners']), is_confidential) # Lead Partner
fill_cell(table.cell(22, 0), str(row['Other Firms/counsels Involved']), is_confidential) # Other Involved Firms
fill_cell(table.cell(24, 0), str(row['Description (in 500 words)']), is_confidential) # Description
code
print(f"Table filled with {'Yes' if is_confidential else 'No'} form data.")
else:
print(f"Warning: Table has only {len(table.rows)} rows. Expected at least 25.")
except IndexError as e:
print(f"Error: Unable to fill the table. {e}")
def fill_cell(cell, text, is_confidential, style=None):
# Clear existing content by deleting each paragraph
for paragraph in cell.paragraphs:
cell._element.remove(paragraph._element)
code
# Adding a new paragraph to the cell
p = cell.add_paragraph()
run = p.add_run(text)
if style == 'special':
# Applying the special style
run.font.size = Pt(14) # Font size 14
run.bold = True # Bold
run.font.name = 'Cambria' # Font family
run.font.color.rgb = RGBColor(255, 255, 255) # White color
p.alignment = 1 # Centre alignment
else:
if is_confidential:
run.font.color.rgb = RGBColor(255, 0, 0) # Set the font color to red
else:
run.font.color.rgb = RGBColor(0, 0, 0) # Default font color
# Set font name for all text in the cell
for run in p.runs:
run.font.name = 'Cambria'
def combine_word_documents(files, output_path):
"""
Combines multiple Word documents into one.
The first file becomes the base document, and each subsequent file's content is added to it.
"""
if not files:
print("No files to combine.")
return
code
print(f"Combining {len(files)} documents...")
# Create a new document for merging
merged_document = Document()
# Iterate through the list of files
for i, file in enumerate(files):
print(f"Adding content from {file}")
try:
sub_doc = Document(file)
# Check if the document is not empty (has paragraphs)
if len(sub_doc.paragraphs) > 0:
# Add a page break before adding content, except for the first document
if i > 0:
merged_document.add_page_break()
# Copy all elements from the subdocument without adding empty paragraphs
for element in sub_doc.element.body:
# Don't copy the section break
if element.tag != qn('w:sectPr'):
merged_document.element.body.append(element)
else:
print(f"Warning: Document {file} is empty and will not be added.")
except Exception as e:
print(f"Warning: Could not add content from {file}: {e}")
# Save the combined document
merged_document.save(output_path)
print(f"Combined document saved to {output_path}")
Streamlit application
def app():
st.title("IFLR 1000 Form Generator")
code
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
with st.spinner("Processing..."):
# Save the uploaded Excel file temporarily
temp_excel_path = "temp_uploaded_file.xlsx"
with open(temp_excel_path, "wb") as f:
f.write(excel_file.getbuffer())
# Output path
output_file = r"C:\Users\Administrator\Desktop\output.docx"
# Call the populate_chambers function
populate_chambers(temp_excel_path, output_file)
# Provide a link to download the output file
if os.path.exists(output_file):
st.success("Forms filled successfully! You can download it below.")
with open(output_file, "rb") as f:
st.download_button(
"Download Filled Form",
f,
file_name="IFLR_Output.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the output file.")
# Clean up the temporary file
os.remove(temp_excel_path)
else:
st.error("Please upload the Excel file.")
if name == "main":
app() give a download button like this in the previous code u genetrted
To implement a download button in your Streamlit application similar to the one in the previous example, you'll need to modify the download functionality in your Streamlit app to allow users to download the combined output document after it has been generated.
Here's how you can integrate the Streamlit interface with an option to download the output file after processing:
python
import pandas as pd
from docx import Document
from docx.shared import RGBColor, Pt
import os
from docx.oxml.ns import qn
import streamlit as st
# Hardcoded paths for the Word templates
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Iflr_Yes.docx" # Template for Yes rows
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Iflr_No.docx" # Template for No rows
def populate_chambers(excel_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
confidential_count = 0
non_confidential_count = 0
# Create directories for temporary files if they don't exist
temp_dir = os.path.join(os.path.dirname(output_path), "temp")
os.makedirs(temp_dir, exist_ok=True)
yes_files = []
no_files = []
# Iterate through each row of the DataFrame
for i, row in df.iterrows():
confidential_val = str(row.get('Confidential / Publishable ', '')).strip()
if confidential_val.lower() == 'yes' and confidential_count < 10:
confidential_count += 1
doc = Document(TEMPLATE_PATH_YES)
if doc.tables:
table = doc.tables[0]
fill_table_with_data(row, table, True, confidential_count)
temp_file = os.path.join(temp_dir, f"yes_{i}.docx")
doc.save(temp_file)
yes_files.append(temp_file)
print(f"Created 'Yes' document for row {confidential_count}")
elif confidential_val.lower() == 'no' and non_confidential_count < 10:
non_confidential_count += 1
doc = Document(TEMPLATE_PATH_NO)
if doc.tables:
table = doc.tables[0]
fill_table_with_data(row, table, False, non_confidential_count)
temp_file = os.path.join(temp_dir, f"no_{i}.docx")
doc.save(temp_file)
no_files.append(temp_file)
print(f"Created 'No' document for row {non_confidential_count}")
combine_word_documents(no_files + yes_files, output_path)
print(f"All documents combined successfully to {output_path}!")
# Clean up temporary files
for file in no_files + yes_files:
try:
os.remove(file)
except Exception as e:
print(f"Warning: Could not delete temporary file {file}: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def fill_table_with_data(row, table, is_confidential, count):
try:
if len(table.rows) >= 25:
fill_cell(table.cell(0, 0), f"Example {min(count, 10)}/10", is_confidential, style='special')
fill_cell(table.cell(2, 0), 'Y' if is_confidential else 'N', is_confidential)
fill_cell(table.cell(6, 0), str(row['Client Name ']), is_confidential)
fill_cell(table.cell(14, 0), str(row['Value ']), is_confidential)
fill_cell(table.cell(20, 0), str(row['Lead partners']), is_confidential)
fill_cell(table.cell(22, 0), str(row['Other Firms/counsels Involved']), is_confidential)
fill_cell(table.cell(24, 0), str(row['Description (in 500 words)']), is_confidential)
print(f"Table filled with {'Yes' if is_confidential else 'No'} form data.")
else:
print(f"Warning: Table has only {len(table.rows)} rows. Expected at least 25.")
except IndexError as e:
print(f"Error: Unable to fill the table. {e}")
def fill_cell(cell, text, is_confidential, style=None):
for paragraph in cell.paragraphs:
cell._element.remove(paragraph._element)
p = cell.add_paragraph()
run = p.add_run(text)
if style == 'special':
run.font.size = Pt(14)
run.bold = True
run.font.name = 'Cambria'
run.font.color.rgb = RGBColor(255, 255, 255)
p.alignment = 1
else:
if is_confidential:
run.font.color.rgb = RGBColor(255, 0, 0)
else:
run.font.color.rgb = RGBColor(0, 0, 0)
for run in p.runs:
run.font.name = 'Cambria'
def combine_word_documents(files, output_path):
if not files:
print("No files to combine.")
return
print(f"Combining {len(files)} documents...")
merged_document = Document()
for i, file in enumerate(files):
print(f"Adding content from {file}")
try:
sub_doc = Document(file)
if len(sub_doc.paragraphs) > 0:
if i > 0:
merged_document.add_page_break()
for element in sub_doc.element.body:
if element.tag != qn('w:sectPr'):
merged_document.element.body.append(element)
else:
print(f"Warning: Document {file} is empty and will not be added.")
except Exception as e:
print(f"Warning: Could not add content from {file}: {e}")
merged_document.save(output_path)
print(f"Combined document saved to {output_path}")
# Streamlit application
def app():
st.title("IFLR 1000 Form Generator")
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
with st.spinner("Processing..."):
temp_excel_path = "temp_uploaded_file.xlsx"
with open(temp_excel_path, "wb") as f:
f.write(excel_file.getbuffer())
output_file = r"C:\Users\Administrator\Desktop\output.docx"
populate_chambers(temp_excel_path, output_file)
if os.path.exists(output_file):
st.success("Forms filled successfully! You can download it below.")
with open(output_file, "rb") as f:
st.download_button(
"Download Filled Form",
f,
file_name="IFLR_Output.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Failed to create the output file.")
os.remove(temp_excel_path)
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
app()
Key Changes for Download Button
Replaced the output link with a download button (st.download_button()) when the output file is successfully created. This allows users to download the generated document directly through the Streamlit UI.
The path for saving the output document is still hardcoded to C:\Users\Administrator\Desktop\output.docx, so make sure you have appropriate permissions for this location.
Running the Code
You can run this Streamlit application like before:
bash
streamlit run your_script_name.py
Replace your_script_name.py with the filename of your Python script. The application will allow you to upload an Excel file and generate a Word document with a download button for the output.
import os
import pandas as pd
from docx import Document
from datetime import datetime
import shutil
# Process each row in the Excel file
for index, row in df.iterrows():
# Load the template for each row
doc = Document(template_file)
# Extract data from the Excel row and handle NaN values
client_name = row.get('Client Name ', '') if pd.notna(row.get('Client Name ', '')) else ''
matter_overview = row.get('Matter/Case Overview', '') if pd.notna(row.get('Matter/Case Overview', '')) else ''
description = row.get('Description (in 500 words)', '') if pd.notna(row.get('Description (in 500 words)', '')) else ''
value = row.get('Value ', '') if pd.notna(row.get('Value ', '')) else ''
lead_partners = row.get('Lead partners', '') if pd.notna(row.get('Lead partners', '')) else ''
Team_partners = row.get('Team Members', '') if pd.notna(row.get('Team Members', '')) else ''
Dates = row.get('Current Status (ongoing / completed )', '') if pd.notna(row.get('Current Status (ongoing / completed )', '')) else ''
publishable = row.get('Confidential / Publishable', '') if pd.notna(row.get('Confidential / Publishable', '')) else ''
if len(doc.tables) > 0:
table = doc.tables[0]
# Client Name
table.cell(3, 0).text = client_name
# Matter description
matter_text = f"{matter_overview}\n\n{description}"
table.cell(5, 0).text = matter_text
# Deal value
table.cell(6, 1).text = str(value)
# Lead partner(s)
table.cell(9, 0).text = lead_partners
table.cell(13, 0).text = Team_partners
table.cell(16, 3).text = Dates
# Create a temporary filename
clean_client_name = ''.join(c for c in client_name if c.isalnum() or c in [' ', '_']).replace(' ', '_')
temp_filename = os.path.join(temp_dir, f"{clean_client_name}.docx")
# Save the populated document to the temporary directory
doc.save(temp_filename)
print(f"Created temporary document: {temp_filename}")
def combine_documents(temp_dir, output_file):
code
combined_doc = Document()
for filename in os.listdir(temp_dir):
if filename.endswith('.docx'):
file_path = os.path.join(temp_dir, filename)
sub_doc = Document(file_path)
# Loop through each element in the sub-doc and copy it to the combined document
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_file)
print(f"Combined document created: {output_file}")
if name == "main":
main() in this code u have ot make a download button
To add a download button in the context of your existing code, you would typically use a framework that supports a user interface, such as Streamlit, Flask, or Django. Below, I'll show you how to convert your script into a Streamlit application that allows users to upload an Excel file, process it, and then download the combined document.
Here's how to modify your code:
Add Streamlit: Install Streamlit in your environment if you haven't done so already, using:
bash
pip install streamlit
Create a Streamlit App: Below is the modified code that integrates your workflow into a Streamlit application:
python
import os
import pandas as pd
from docx import Document
import streamlit as st
import tempfile
def populate_docx_template(excel_file, template_file, temp_dir):
# Load Excel data
df = pd.read_excel(excel_file)
# Process each row in the Excel file
for index, row in df.iterrows():
# Load the template for each row
doc = Document(template_file)
# Extract data from the Excel row and handle NaN values
client_name = row.get('Client Name ', '') if pd.notna(row.get('Client Name ', '')) else ''
matter_overview = row.get('Matter/Case Overview', '') if pd.notna(row.get('Matter/Case Overview', '')) else ''
description = row.get('Description (in 500 words)', '') if pd.notna(row.get('Description (in 500 words)', '')) else ''
value = row.get('Value ', '') if pd.notna(row.get('Value ', '')) else ''
lead_partners = row.get('Lead partners', '') if pd.notna(row.get('Lead partners', '')) else ''
team_partners = row.get('Team Members', '') if pd.notna(row.get('Team Members', '')) else ''
dates = row.get('Current Status (ongoing / completed )', '') if pd.notna(row.get('Current Status (ongoing / completed )', '')) else ''
publishable = row.get('Confidential / Publishable', '') if pd.notna(row.get('Confidential / Publishable', '')) else ''
if len(doc.tables) > 0:
table = doc.tables[0]
# Client Name
table.cell(3, 0).text = client_name
# Matter description
matter_text = f"{matter_overview}\n\n{description}"
table.cell(5, 0).text = matter_text
# Deal value
table.cell(6, 1).text = str(value)
# Lead partner(s)
table.cell(9, 0).text = lead_partners
table.cell(13, 0).text = team_partners
table.cell(16, 3).text = dates
# Create a temporary filename
clean_client_name = ''.join(c for c in client_name if c.isalnum() or c in [' ', '_']).replace(' ', '_')
temp_filename = os.path.join(temp_dir, f"{clean_client_name}.docx")
# Save the populated document to the temporary directory
doc.save(temp_filename)
def combine_documents(temp_dir, output_file):
combined_doc = Document()
for filename in os.listdir(temp_dir):
if filename.endswith('.docx'):
file_path = os.path.join(temp_dir, filename)
sub_doc = Document(file_path)
# Loop through each element in the sub-doc and copy it to the combined document
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_file)
def main():
st.title("Document Generator")
# Upload the Excel file
excel_file = st.file_uploader("Upload your Excel file", type=["xlsx", "xls"])
if st.button("Generate Document"):
if excel_file is not None:
with tempfile.TemporaryDirectory() as temp_dir:
# Save the uploaded Excel file to a temporary location
temp_excel_path = os.path.join(temp_dir, "uploaded_excel.xlsx")
with open(temp_excel_path, "wb") as f:
f.write(excel_file.getbuffer())
# Use a hardcoded template path for demonstration
template_file = r'c:\Users\Administrator\Desktop\legal500.docx'
output_file = os.path.join(temp_dir, "combined_output.docx")
# Generate documents
populate_docx_template(temp_excel_path, template_file, temp_dir)
combine_documents(temp_dir, output_file)
# Provide a link to download the output file
with open(output_file, "rb") as f:
st.download_button(
label="Download Combined Document",
data=f,
file_name="combined_output.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload an Excel file.")
if __name__ == "__main__":
main()
Key Features in the Streamlit Application
File Upload: Allows users to upload an Excel file which contains the data needed to populate the document.
Processing Button: When the user clicks "Generate Document," the application processes the uploaded Excel file using the existing logic for populating the Word template.
Temporary Directory Management: Utilizes Python's tempfile module to handle temporary directories for uploaded files. This ensures that files are properly cleaned up after the session is done.
Download Button: After generating the combined document, it provides a download button for the user to download the resulting document directly from the Streamlit UI.
Run the Application
After saving the code to a Python file (e.g., app.py), run the Streamlit application with:
bash
streamlit run app.py
Additional Note
Be sure to have the legal500.docx file at the specified path unless you change it to a path that exists on your system. The application will create and clean up temporary files during execution.