1

I have an Excel file with a list of clients, including their name, document number, credit card number, and company. For each client, I need to create a PDF file with the values from the table. First, I transform some values in the table, then create a Word file, then transform these Word files into PDFs, and finally, I send all the PDFs via email. There may be two different companies, and for each one, there is a different Word file that I need to use. I need it to recognize the company of each client and choose the appropriate Word file based on that data. For some reason, it doesn't alternate between the Word files and only selects the first one.

from pathlib import Path
import datetime as dt
import pandas as pd
from docxtpl import DocxTemplate
from docx2pdf import convert
import os
import smtplib
from email.mime.text import MIMEText
import os
import smtplib
from email.message import EmailMessage

df = pd.read_excel("Listado libre de deuda.xlsx")

df["FECHA"] = format(dt.date.today(), '%d/%m/%Y')
df["NOMBRE"] = df["NOMBRE"].str.lower()
df["NOMBRE"] = df["NOMBRE"].str.title()
formato_miles = lambda x: '{:,.0f}'.format(x)
df["DNI"] = df["DNI"].apply(formato_miles)
df["DNI"] = df["DNI"].str.replace(',', '.')

base_dir = Path(__file__).parent
for _, row in df.iterrows():
    empresa = row["EMPRESA"]
    if empresa == "finares":
        word_template_path = base_dir / "Libre de deuda Finares.docx"
    else:
        word_template_path = base_dir / "Libre de deuda Fideicomiso.docx"
excel_path = base_dir / "Listado libre de deuda.xlsx"
output_dir = base_dir / "Libres de deuda"

output_dir.mkdir(exist_ok=True)

for record in df.to_dict(orient="records"):
    doc = DocxTemplate(word_template_path)
    doc.render(record)
    output_path = output_dir / f"{record['NOMBRE']}.docx"
    doc.save(output_path)
    convert(output_path)

os.chdir("C:\Python\Python311\Finares Alycbur\Libres de deuda")
for archivo in os.listdir():
    if archivo.endswith('.docx'):
        os.remove(archivo)

email = 'random'
password = "xxxxxx"
to_email = ['random2']

folder_path = r"C:\Python\Python311\Finares Alycbur\Libres de deuda"
file_names = os.listdir(folder_path)

msg = EmailMessage()
msg['Subject'] = 'Libres de deuda USAR ESTE'
msg['From'] = email
msg['To'] = ", ".join(to_email)
msg.attach(MIMEText('Se adjuntan los libres de deuda solicitados!\n\nSaludos!'))

for file_name in file_names:
    with open(os.path.join(folder_path, file_name), 'rb') as f:
        file_data = f.read()
        msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
    smtp.starttls()
    smtp.login(email, password)
    smtp.send_message(msg)
edi9999
  • 19,701
  • 13
  • 88
  • 127

0 Answers0