最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - using docx to replace placeholders for a standardized report - Stack Overflow

programmeradmin5浏览0评论

I am trying to change a project report to a template. However, not all placeholders work. Here is the sample text I am trying to replace:

The section of the template I have trouble replacing

Here is what I get out of running the code:

Results -- some placeholders work and others do not

Here are the documents in a public folder:

Replacement list:
replacement values

Here is the code:

`from docx import Document
import pandas as pd
import os

def load_data(file_path):
    """Load data from CSV file."""
    try:
        df = pd.read_csv(file_path)
        
        # Use first two columns regardless of names
        if len(df.columns) >= 2:
            first_col, second_col = df.columns[0], df.columns[1]
            
            # Clean up the data
            df[first_col] = df[first_col].astype(str).str.strip()
            df[second_col] = df[second_col].fillna("").astype(str).str.strip()
            
            return dict(zip(df[first_col], df[second_col]))
        else:
            raise ValueError("CSV file must have at least 2 columns")
            
    except Exception as e:
        print(f"Error reading CSV file: {file_path}")
        print(f"Error details: {str(e)}")
        raise

def replace_placeholders(doc, data):
    """Replace placeholders in document with values from data."""
    for paragraph in doc.paragraphs:
        for run in paragraph.runs:
            for key, value in data.items():
                placeholder = f"<<{key}>>"
                if placeholder in run.text:
                    run.text = run.text.replace(placeholder, str(value))

def generate_report(template_path, output_path, data_path):
    """Generate report from template using data."""
    try:
        # Remove existing output file if it exists
        if os.path.exists(output_path):
            os.remove(output_path)
            print(f"Removed existing output file: {output_path}")
        
        # Load data and create report
        data = load_data(data_path)
        print(f"Loaded {len(data)} replacements from CSV")
        
        doc = Document(template_path)
        replace_placeholders(doc, data)
        doc.save(output_path)
        print(f"Report generated: {output_path}")
        
    except Exception as e:
        print(f"Error generating report: {str(e)}")
        raise

# File paths
template_path = r"C:\xxxxx\Test4.docx"
output_path = r"C:\\xxxxx\\generated_acquisition_report.docx"
data_path = r"C:\\xxxxx\\data2.csv"  # Changed to .csv

if __name__ == "__main__":
    generate_report(template_path, output_path, data_path) `

I have tried modifying my placeholders by taking out spaces, used dashes, all sorts of things and it doesn't work. Even when I try "rebuilding" the project document and doing it page by page it doesn't like the placeholders on the front page.

Thank you for your help. Larks

发布评论

评论列表(0)

  1. 暂无评论