populate_chambers(excel_path, doc_path, output_path)
in this code in some forms in the pdf is not going to correct cells ...so now i will two one one page doc one for publishable mattters and other for confidential matters ....now make one one row enetry ...for each row fill the same one page doc and at the end cmbine all the docs ....like if excel have 10publisbale and 10 confidential rows ..in end combine all thwse 20 forms ....and deelte the temproray saved single single upadetd doc
Assistant
Certainly! To achieve your requirement of populating individual one-page documents for each entry in your Excel file—both publishable and confidential matters—and then combining them into a single document, you can follow these steps:
Generate individual Word documents for each entry.
Save the individual documents temporarily.
Merge all these documents into a final combined document.
Clean up the temporary documents after merging.
Here's how you might modify your existing code:
python
User
this is doing right bbut in the one page doc that i provided chambers.doc in cell 0 of table their is publishable matter 1 ....and now its same 1 in all the other forms also ...so is it possible taht we chges this for each row like for row 1 ist publishable matter 1 and then replace 1 with 2 for ext and so on
Assistant
Yes, you can modify the code to replace the first cell of each table with a unique matter identifier, such as "Publishable Matter 1", "Publishable Matter 2", and so on, for each individual document created. You can achieve this by passing the index of the row to the create_individual_document function.
Here's how you can adjust the create_individual_document function and the way you call it to include the matter identifier:
python
User
import pandas as pd
from docx import Document
import os
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
code
# Update the matter identifier in the first cell of the table
doc.tables[0].cell(1, 0).text = f"Publishable Matter {matter_count}"
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
code
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
To ensure that the existing text in the first cell (cell [0, 0]) of your Word document is preserved and only the unique matter identifier (e.g., "1", "2", ...) is updated—appending or replacing the numeric part while maintaining any other text—you can modify the create_individual_document function accordingly.
Here’s how you might adjust your function to achieve this:
Adjusted Code
python
User
its not 0 cell its cell 1 im sorru
Assistant
No problem! If you want to update cell [1, 0] (the second cell in the first column) instead of cell [0, 0], you can simply adjust the indexing in the create_individual_document function. Here’s the modified version of the code that updates cell [1, 0] while preserving any existing text in that cell.
Adjusted Code
python
User
on cell one apply Times new roman fond text size 12 Bold and center align
Assistant
To apply specific formatting (like font type, size, boldness, and alignment) to a particular cell in a Word document using the python-docx library, you can modify the cell's paragraph style. Here's how you can extend the create_individual_document function to apply the desired formatting to cell [1, 0] (the second cell of the first column).
Updated Code with Formatting
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
code
# Update the matter identifier in the specified cell (cell[1, 0])
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier while keeping the other text intact
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the last part with the new number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
# Apply formatting to the specified cell
cell = doc.tables[0].cell(1, 0)
# Set font to Times New Roman, size 12, and bold
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman' # Set font to Times New Roman
run.font.size = Pt(12) # Set font size to 12
run.font.bold = True # Make the font bold
# Center align the text in the cell
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
Assistant
Certainly! To create a Streamlit interface for the functionality you've described, you'll want to set up a basic Streamlit app that allows users to upload their Excel and Word template files. After the user uploads these files, the app will execute the document generation and provide a download link for the combined final document.
Setting Up Streamlit
Before we start, ensure you have Streamlit installed. If you haven't installed it yet, you can do so using pip:
bash
pip install streamlit
Streamlit Application Code
Here’s how you can modify your existing code to include a Streamlit interface:
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
code
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
Assistant
Certainly! To modify the Streamlit application so that users only need to upload the Excel file, while the document template is provided through code, you can set a fixed path to the template file within the Streamlit app.
Below is the updated code where the Word template is hard-coded into the application:
Updated Streamlit Application Code
python
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Path to the Word template
TEMPLATE_PATH = r"C:\Users\Administrator\Desktop\Chambers.docx" # Update this path as needed
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
Assistant
To modify your Streamlit application to only fill the forms for rows that have "No" in their "Confidential" column (assuming you're referring to the "Confidential" column), you'll need to filter your DataFrame based on that condition.
Here’s how to adjust your code:
Filter Rows: Before processing each row, you will check if the "Confidential" column has a value of "No".
Remove the Confidential Matters Section: Since you're focusing only on rows marked "No", the logic that handles the confidential matters can be omitted.
Here’s the modified code:
python
User
no still filling all thw rows
Assistant
If the code is still filling all rows, it might be due to the way the condition is applied. It’s possible that there may be slight inconsistencies in matching the string values in your DataFrame—either leading or trailing whitespaces, casing differences, etc.
Here's how to make sure only the desired rows are processed:
Check for Duplicates: Ensure your Excel file has a column named Confidential and that the values are exactly "No" or "Yes" without leading or trailing spaces.
Use .strip(): Strip the whitespace from the values if present to ensure exact matching.
Convert to Lowercase: It’s a good practice to convert the strings to lower case while checking to avoid casing issues.
Here’s the updated filtering logic in the populate_chambers function:
python
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs = []
# Filter the DataFrame for rows where 'Confidential' column is 'No', using strip and lower
df_filtered = df[df['Confidential'].str.strip().str.lower() == 'no']
# Handle Publishable Matters
for index, row in df_filtered.iterrows(): # Now iterating over the filtered DataFrame
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
User
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
Path to the Word template
TEMPLATE_PATH = r"C:\Users\Administrator\Desktop\Chambers.docx" # Set your path here
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
code
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
Assistant
To accommodate the requirement of filling a different template for rows classified as "Yes" in the "Confidential / Publishable" column and then combining both sets of documents into one final document, you'll need to:
Create a second template variable for the new template.
Filter the DataFrame for the rows with "Yes" in the specified column.
Generate individual documents for both templates based on their respective conditions.
Combine all the documents into one final document.
Here’s how you can implement these changes:
Updated Code
python
User
good but just like publishable matter {matter index} in the cell 1 of the table do that with confidential one also
Assistant
To add a similar identifier for the "Confidential Matter" entries like you did for the "Publishable Matter" entries, you can modify the create_individual_document function slightly. You would want to check which template is being used and insert the appropriate identifier into the relevant cell (cell [1, 0] in both templates).
Here’s how to implement this:
Check the Template: Determine if the function is being called with the "Yes" template or the "No" template.
Set the Identifier Text Accordingly: Use "Confidential Matter {matter index}" for the "Yes" entries and keep "Publishable Matter {matter index}" for the "No" entries.
Updated Code
Here’s the updated create_individual_document function that adds the "Confidential Matter" identifier for rows populated with the "Yes" template:
python
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
# Determine if using "Yes" or "No" template for identifier text
if "Confidential" in template_path: # For the Yes template
identifier_text = f"Confidential Matter {matter_count}"
else: # For the No template
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
import pandas as pd
from docx import Document
from docx import Document as DocxDocument
import os
def create_individual_document(template_path, data, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
# Assume the same structure for populating the document
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = DocxDocument()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_path, doc_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, temporary_output_path)
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# File paths
excel_path = r"C:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx"
doc_path = r"C:\Users\Administrator\Desktop\Submission Form Templates\Templates\Chambers.docx"
output_path = r"C:\Users\Administrator\Desktop\combined_confidential_publishable.docx"
populate_chambers(excel_path, doc_path, output_path)
Explanation:
create_individual_document Function: This function creates an individual Word document using the provided template and fills it with the data from a single row.
combine_documents Function: This function takes a list of document paths and combines them into a single Word document.
populate_chambers Changes: The function now generates individual documents for both the publishable and confidential matters and collects the paths of these documents. After generating all documents, it calls combine_documents to merge them together and then removes the temporary documents.
Note:
Ensure that your Excel file contains a column named 'Confidential' to check for confidential matters correctly.
Adjust the cell indexes in the create_individual_document function to match your Word document's structure.
Clean up of temporary files is handled after the combined document is created.
import pandas as pd
from docx import Document
import os
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
# Update the matter identifier in the first cell of the table
doc.tables[0].cell(0, 0).text = f"Publishable Matter {matter_count}"
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_path, doc_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# File paths
excel_path = r"C:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx"
doc_path = r"C:\Users\Administrator\Desktop\Submission Form Templates\Templates\Chambers.docx"
output_path = r"C:\Users\Administrator\Desktop\combined_confidential_publishable.docx"
populate_chambers(excel_path, doc_path, output_path)
What's Changed:
Adding a Matter Identifier: The create_individual_document function now accepts an additional parameter matter_count, which is the row index + 1 (to start numbering from 1 instead of 0). This value is used to set the text of the first cell in the Word document table (doc.tables[0].cell(0, 0).text).
Adjusting Indexing: The call to create_individual_document within the loops now passes index + 1 to increment the matter count for each document created.
Output:
With these changes, the first cell of each generated document's table will contain a unique identifier indicating its number in the sequence, such as "Publishable Matter 1", "Publishable Matter 2", etc. Similarly, if you add documents for confidential matters, they will also follow the same numbering scheme.
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
populate_chambers(excel_path, doc_path, output_path) in this it is replacing the original written text is cell 0 for cell 0 i wanted that it to only upafdet the text after publisbale matter like for 1 its 1 for 2 its 2 and so on
import pandas as pd
from docx import Document
import os
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
# Update the matter identifier in the first cell of the table
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(0, 0).text # Get existing text
# Replace or append the numeric identifier while keeping the other text intact
if "Publishable Matter" in existing_text:
doc.tables[0].cell(0, 0).text = existing_text.split(" ")[0] + " " + identifier_text.split(" ")[1] # Replace the number
else:
doc.tables[0].cell(0, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_path, doc_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# File paths
excel_path = r"C:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx"
doc_path = r"C:\Users\Administrator\Desktop\Chambers.docx"
output_path = r"C:\Users\Administrator\Desktop\combined_confidential_publishable1.docx"
populate_chambers(excel_path, doc_path, output_path)
Key Changes:
Keeping Existing Text:
The script retrieves the existing text in the first cell and checks if it includes the phrase "Publishable Matter".
If it does, the script replaces only the number part while preserving the rest of the text.
If it doesn't, it appends the new matter identifier as an additional note.
Note:
Ensure that the cell indices (like cell(0, 0), cell(2, 0), etc.) match the structure of your Word document.
You may want to adjust the splitting logic if the structure of the first cell is different than anticipated. The solution assumes that "Publishable Matter" is consistently formatted in the first cell.
import pandas as pd
from docx import Document
import os
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
# Update the matter identifier in the specified cell (cell[1, 0])
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier while keeping the other text intact
if "Publishable Matter" in existing_text:
# Replace the number while keeping the rest of the text intact
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the last part with the new number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_path, doc_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# File paths
excel_path = r"C:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx"
doc_path = r"C:\Users\Administrator\Desktop\Chambers.docx"
output_path = r"C:\Users\Administrator\Desktop\combined_confidential_publishable1.docx"
populate_chambers(excel_path, doc_path, output_path)
Key Changes:
Updating the Correct Cell:
The line getting the existing text now retrieves it from doc.tables[0].cell(1, 0).
The logic for modifying this text has been retained, but it's now accurately affecting the second cell in the first column as requested.
Summary:
The adjusted code now updates the designated cell ([1, 0]) to replace the matter count correctly while keeping any other text intact.
This way, each document maintains any existing content and only updates the specific identifier at the front.
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
# Update the matter identifier in the specified cell (cell[1, 0])
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier while keeping the other text intact
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the last part with the new number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
# Apply formatting to the specified cell
cell = doc.tables[0].cell(1, 0)
# Set font to Times New Roman, size 12, and bold
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman' # Set font to Times New Roman
run.font.size = Pt(12) # Set font size to 12
run.font.bold = True # Make the font bold
# Center align the text in the cell
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_path, doc_path, output_path):
try:
print("Loading Excel data...")
df = pd.read_excel(excel_path)
print(f"Excel data loaded: {len(df)} rows")
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# File paths
excel_path = r"C:\Users\Administrator\Documents\Submissions- Arbitration (version 1).xlsb.xlsx"
doc_path = r"C:\Users\Administrator\Desktop\Chambers.docx"
output_path = r"C:\Users\Administrator\Desktop\combined_confidential_publishable1.docx"
populate_chambers(excel_path, doc_path, output_path)
Key Changes for Formatting:
Font Settings:
The font is set to "Times New Roman", size 12, and bold using the run.font properties.
Center Alignment:
The alignment of the paragraph in cell [1, 0] is set to center by using cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER.
Summary:
This code will now ensure that the desired cell format is applied correctly to cell [1, 0] in every generated document while keeping the existing content and updating the matter count as specified.
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
code
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
# Create a list to store paths of individual documents
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Now if you have confidential matters, do them similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes": # Check confidentiality column
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_path, row, index + 1, temporary_output_path) # Pass index + 1 for matter count
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
populate_chambers(excel_path, doc_path, output_path) in this add s streamlit inetrface where it takes these two input files and provide and outptut file ....same implentaion just a interface i want
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
def create_individual_document(template_path, data, matter_count, output_path):
""" Create an individual document for a row of data based on a template """
doc = Document(template_path)
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
""" Combine multiple documents into a single document """
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, doc_file, output_path):
""" Generate the documents based on the Excel input """
try:
df = pd.read_excel(excel_file)
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_file, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Now handle Confidential Matters similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes":
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_file, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# Streamlit application
def main():
st.title("Chambers Document Generator")
# User uploads
excel_file = st.file_uploader("Upload Excel File", type=["xlsx", "xls"])
doc_file = st.file_uploader("Upload Word Template File", type=["docx"])
if st.button("Generate Document"):
if excel_file and doc_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, doc_file, output_path)
st.success("Document generated successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Combined Document",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload both files.")
if __name__ == "__main__":
main()
Explanation of the Code:
Streamlit Setup:
The main function initializes the Streamlit app with file upload options for an Excel file and a Word template.
st.file_uploader is used to allow users to upload the required files.
Document Generation:
When the "Generate Document" button is clicked, the populate_chambers function is called with the uploaded files as input. This function processes the files as per your logic.
After generating the document, a success message is displayed, and the user is provided with a download button to download the combined document.
Error Handling:
Basic error handling is included to check if both files are uploaded before processing.
Running the Streamlit App
To run the Streamlit app, save the above code into a Python file (for example, app.py), and then run the following command in your terminal:
bash
streamlit run app.py
This will launch a new browser window with the Streamlit interface where you can upload your files and generate the combined document.
code
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, doc_file, output_path):
""" Generate the documents based on the Excel input """
try:
df = pd.read_excel(excel_file)
individual_docs = []
code
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(doc_file, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Now handle Confidential Matters similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes":
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(doc_file, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
Streamlit application
def main():
st.title("Chambers forms")
code
# User uploads
excel_file = st.file_uploader("Upload Excel File", type=["xlsx", "xls"])
doc_file = st.file_uploader("Upload Word Template File", type=["docx"])
if st.button("Generate Document"):
if excel_file and doc_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, doc_file, output_path)
st.success("Document generated successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Combined Document",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload both files.")
if name == "main":
main() in this add one only upalod excel .....the doc template also provide through code
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Path to the Word template
TEMPLATE_PATH = "path/to/your/Chambers.docx" # Update this path as needed
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
"""Combine multiple documents into a single document."""
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs = []
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Now handle Confidential Matters similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes":
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# Streamlit application
def main():
st.title("Chambers Document Generator")
# User uploads
excel_file = st.file_uploader("Upload Excel File", type=["xlsx", "xls"])
if st.button("Generate Document"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
st.success("Document generated successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Combined Document",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
main()
Key Changes:
Hardcoded Word Template Path: The path to the Word document template is set in the variable TEMPLATE_PATH. Make sure to update this with the actual path to your Chambers.docx file on your filesystem.
Single File Upload: The file uploader for the Word template has been removed. The user only needs to upload the Excel file.
Populate Chambers Function: The call to create_individual_document now uses the hardcoded TEMPLATE_PATH instead of requiring user input for the Word file.
Note:
Make sure that the template file (Chambers.docx) exists at the specified path before running the Streamlit application.
This application will now prompt users to upload only the Excel file and will generate the required documents based on the template specified in your code.
def combine_documents(document_paths, output_path):
"""Combine multiple documents into a single document."""
combined_doc = Document()
code
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs = []
code
# Handle Publishable Matters
for index, row in df.iterrows():
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Now handle Confidential Matters similarly
for index, row in df.iterrows():
if row.get('Confidential', 'No') == "Yes":
temporary_output_path = f"temp_confidential_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
code
# User uploads
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
st.success("Form filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Filled Form",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload the Excel file.")
if name == "main":
main() in this make chnges to fill only those rows which have No in their confidential/pUblisable column ....for yes the form is differnt for now i want only the no one
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Path to the Word template
TEMPLATE_PATH = r"C:\Users\Administrator\Desktop\Chambers.docx" # Set your path here
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
"""Combine multiple documents into a single document."""
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs = []
# Filter the DataFrame for rows where 'Confidential' column is 'No'
df_filtered = df[df['Confidential'] == 'No']
# Handle Publishable Matters
for index, row in df_filtered.iterrows(): # Now iterating over the filtered DataFrame
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
# User uploads
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
st.success("Form filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Filled Form",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
main()
Key Modifications:
Filter the DataFrame: Before processing rows, the code now filters df for entries where the "Confidential" column equals "No" using df_filtered = df[df['Confidential'] == 'No']. This means that only rows with "No" in the "Confidential" column will be processed for document generation.
Iterate Over Filtered DataFrame: The loop that generates individual documents now iterates over df_filtered instead of the entire original DataFrame, ensuring that only relevant rows are used.
This setup will create documents only for those entries listed as "No" in the specified column. If you need additional changes or functionality, feel free to ask!
Key Changes:
Stripping and Lowercasing: The condition now uses df['Confidential'].str.strip().str.lower() == 'no' to ensure that any leading or trailing whitespace is ignored, and casing does not affect the filtering.
Ensure that the column name in the DataFrame matches exactly what you have in the Excel file, including spacing and casing.
Steps to Check:
Confirm that the Excel file does indeed have a column labeled Confidential, and it has either "No" or "Yes" with the expected format.
You might want to print out the filtered DataFrame to see what rows remain after filtering, e.g., after filtering, you can add st.write(df_filtered) to your Streamlit app to debug.
Testing:
To ensure the filter works as expected, you can use the following code to print out the filtered DataFrame right before generating the documents:
python
print("Filtered DataFrame:")
print(df_filtered)
Results:
This change should restrict the document generation to only those rows where the value in the Confidential column is "No". If you're still facing issues, please check the contents of your Excel file carefully for any discrepancies.
def combine_documents(document_paths, output_path):
"""Combine multiple documents into a single document."""
combined_doc = Document()
code
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs = []
code
# Filter the DataFrame for rows where 'Confidential' column is 'No', using strip and lower
df_filtered = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
# Handle Publishable Matters
for index, row in df_filtered.iterrows(): # Now iterating over the filtered DataFrame
temporary_output_path = f"temp_publishable_{index}.docx"
create_individual_document(TEMPLATE_PATH, row, index + 1, temporary_output_path)
individual_docs.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs, output_path)
# Clean up temporary documents
for doc_path in individual_docs:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
code
# User uploads
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
st.success("Form filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Filled Form",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload the Excel file.")
if name == "main":
main() this is working fine and now i have one more template whose only color is diff but we have to fill the Yes rows for ocnfidential/publishable columns in it at end combine the current one and the new template all orms tohgtehr
import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st
# Paths to the Word templates
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx" # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers_Confidential.docx" # Template for Yes rows
def create_individual_document(template_path, data, matter_count, output_path):
"""Create an individual document for a row of data based on a template."""
doc = Document(template_path)
identifier_text = f"Publishable Matter {matter_count}"
existing_text = doc.tables[0].cell(1, 0).text # Get existing text from cell [1, 0]
# Replace or append the numeric identifier
if "Publishable Matter" in existing_text:
parts = existing_text.split(" ")
parts[-1] = str(matter_count) # Update the number
doc.tables[0].cell(1, 0).text = " ".join(parts)
else:
doc.tables[0].cell(1, 0).text = f"{existing_text} | {identifier_text}" # Append if not found
cell = doc.tables[0].cell(1, 0)
# Apply the specified formatting
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.name = 'Times New Roman'
run.font.size = Pt(12)
run.font.bold = True
cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# Populate the rest of the document with the provided data
doc.tables[0].cell(2, 0).text = f" {data['Client Name ']}"
doc.tables[0].cell(3, 0).text = f" {data['Description (in 500 words)']}"
doc.tables[0].cell(4, 0).text = f" {data['Value ']}"
doc.tables[0].cell(6, 0).text = f" {data['Lead partners']}"
doc.tables[0].cell(7, 0).text = f" {data['Team Members']}"
doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved']}"
doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )']}"
doc.save(output_path)
print(f"Saved individual document: {output_path}")
def combine_documents(document_paths, output_path):
"""Combine multiple documents into a single document."""
combined_doc = Document()
for doc_path in document_paths:
sub_doc = Document(doc_path)
for element in sub_doc.element.body:
combined_doc.element.body.append(element)
combined_doc.save(output_path)
print(f"Combined document saved: {output_path}")
def populate_chambers(excel_file, output_path):
"""Generate the documents based on the Excel input."""
try:
df = pd.read_excel(excel_file)
individual_docs_no = []
individual_docs_yes = []
# Filter the DataFrame for rows
df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']
# Handle Publishable Matters for 'No' rows
for index, row in df_no.iterrows():
temporary_output_path = f"temp_publishable_no_{index}.docx"
create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temporary_output_path)
individual_docs_no.append(temporary_output_path)
# Handle Publishable Matters for 'Yes' rows
for index, row in df_yes.iterrows():
temporary_output_path = f"temp_publishable_yes_{index}.docx"
create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temporary_output_path)
individual_docs_yes.append(temporary_output_path)
# Combine all individual documents into one
combine_documents(individual_docs_no + individual_docs_yes, output_path)
# Clean up temporary documents
for doc_path in individual_docs_no + individual_docs_yes:
os.remove(doc_path)
print("Temporary documents cleaned up.")
except Exception as e:
print(f"Unexpected error: {e}")
# Streamlit application
def main():
st.title("Fill Chambers and Partners Form")
# User uploads
excel_file = st.file_uploader("Upload Submission Excel File", type=["xlsx", "xls"])
if st.button("Fill the Template"):
if excel_file:
output_path = "combined_confidential_publishable.docx"
populate_chambers(excel_file, output_path)
st.success("Forms filled successfully!")
# Provide download link
with open(output_path, "rb") as f:
btn = st.download_button(
label="Download Filled Form",
data=f,
file_name="combined_confidential_publishable.docx",
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
else:
st.error("Please upload the Excel file.")
if __name__ == "__main__":
main()
Key Changes
Two Template Paths:
A new constant TEMPLATE_PATH_YES is defined for the template used when the "Confidential / Publishable" column has a value of "Yes".
Separate Filtering:
Two DataFrames are created: df_no for rows with "No" and df_yes for rows with "Yes".
Iterate Over Both Filtered DataFrames:
The code generates individual documents for both filtered DataFrames by calling create_individual_document with the relevant template for each case.
Combining All Documents:
The combine_documents function now combines documents from both the "No" and "Yes" groups into a single document for download.
This setup allows you to fill out two different templates based on the specified conditions in your Excel sheet, and then combine all the generated documents into one final document that can be downloaded through the Streamlit interface. Adjust the path to TEMPLATE_PATH_YES as needed. Make sure both templates are correctly formatted to match the expected structure as used in your code.
Changes Explained
The function now checks if the template being used is the one for confidential matters (i.e., if it contains "Confidential" in its path).
It sets the identifier_text accordingly. For the "Yes"-template, it sets it to "Confidential Matter {matter_count}", and for the "No"-template, it keeps it as "Publishable Matter {matter_count}".
Everything else about creating the documents remains the same.
With this update, each of your generated documents will now include the appropriate identifier in cell [1, 0], depending on whether the row is classified as confidential or publishable. Make sure both templates are structured similarly to accommodate this new identifier.