如何将Django模型数据作为Excel文件附加并将其作为邮件发送给SMTP

发布于 2025-02-07 14:38:30 字数 1986 浏览 1 评论 0原文

我在Django模型中有一些数据,我想从该数据中创建Excel文件,并将其附加在SMTP中,并将其发送给目标用户。 我还使用django-import-export来导出excel文件。但是在这种情况下,我想在电子邮件中附加文件。

模型

class FinalBill(models.Model):
shipDate = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
customerReference = models.CharField(max_length = 200, blank = True, null = True)
customerConfirmation = models.CharField(max_length = 200, blank = True, null = True)
deliveryConfirmation = models.CharField(max_length = 200, blank = True, null = True)
address = models.CharField(max_length = 200, blank = True, null = True)
service = models.CharField(max_length = 200, blank = True, null = True)
weight = models.FloatField(blank = True, null = True)
pricingZone = models.CharField(max_length = 200, blank = True, null = True)
uspsCompRate = models.FloatField(blank = True, null = True)
charges = models.FloatField(blank = True, null = True)
surcharges = models.FloatField(blank = True, null = True)
totalSavings = models.FloatField(blank = True, null = True)
totalCharges = models.FloatField(blank = True, null = True)
customerID = models.CharField(max_length = 200)
is_exported = models.BooleanField(default=False)
exported_date = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
def __str__(self):
    return str(self.deliveryConfirmation)

utills.py

def send_bill_on_mail(mailerID):
   customerBill = FinalBill.objects.filter(customerID=mailerID, is_exported=False)
   dataset = Bills().export(customerBill)
   mail_subject = "Subject Name"
   message = "Test Email Message"
   to_email = "[email protected]"
   file = "file"        
   mail = EmailMessage(mail_subject, message,  settings.EMAIL_HOST_USER, [to_email])
   mail.attach(file.name, file.read(), file.content_type)
   mail.send()

i have some data in django models and i want to make excel file from that data and attach it in SMTP as file and send it to target user.
i am also using django-import-export to export the excel files .but in this case i want to attach the file in email.

Model

class FinalBill(models.Model):
shipDate = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
customerReference = models.CharField(max_length = 200, blank = True, null = True)
customerConfirmation = models.CharField(max_length = 200, blank = True, null = True)
deliveryConfirmation = models.CharField(max_length = 200, blank = True, null = True)
address = models.CharField(max_length = 200, blank = True, null = True)
service = models.CharField(max_length = 200, blank = True, null = True)
weight = models.FloatField(blank = True, null = True)
pricingZone = models.CharField(max_length = 200, blank = True, null = True)
uspsCompRate = models.FloatField(blank = True, null = True)
charges = models.FloatField(blank = True, null = True)
surcharges = models.FloatField(blank = True, null = True)
totalSavings = models.FloatField(blank = True, null = True)
totalCharges = models.FloatField(blank = True, null = True)
customerID = models.CharField(max_length = 200)
is_exported = models.BooleanField(default=False)
exported_date = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
def __str__(self):
    return str(self.deliveryConfirmation)

Utills.py

def send_bill_on_mail(mailerID):
   customerBill = FinalBill.objects.filter(customerID=mailerID, is_exported=False)
   dataset = Bills().export(customerBill)
   mail_subject = "Subject Name"
   message = "Test Email Message"
   to_email = "[email protected]"
   file = "file"        
   mail = EmailMessage(mail_subject, message,  settings.EMAIL_HOST_USER, [to_email])
   mail.attach(file.name, file.read(), file.content_type)
   mail.send()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以往的大感动 2025-02-14 14:38:30
def export_data_to_excel(mailerID) -> None: 
  excelfile = BytesIO()
  workbook = Workbook()
  workbook.remove(workbook.active)
  worksheet = workbook.create_sheet(title='Title Name', index=1)

  bill_queryset =  Bills.objects.filter(cus_id=mailerID, is_exported=False)
  columns = ['Date', 'Reference', 'Confirmation', 'Confirmation', 'Address', 'Service', 'Weight', 'Pricing Zone', 'UspsRate', 'Charges', 'Sur Charges', 'Total Savings', 'Total Charges', 'Customer ID']
  row_num = 1

# Assign the titles for each cell of the header
  for col_num, column_title in enumerate(columns, 1):
    cell = worksheet.cell(row=row_num, column=col_num)
    cell.value = column_title
    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=False)
    cell.font = Font(bold=True)
# Iterate through all coins
 for _, bill in enumerate(bill_queryset, 1):
    row_num += 1

    # Define the data for each cell in the row
    row = [
        bill.shipDate,
        bill.customerReference,
        bill.customerConfirmation,
        bill.deliveryConfirmation,
        bill.address,
        bill.service,
        bill.weight,
        bill.pricingZone,
        bill.uspsCompRate,
        bill.charges,
        bill.surcharges,
        bill.totalSavings,
        bill.totalCharges,
        bill.customerID,
    ]

    # Assign the data for each cell of the row
    for col_num, cell_value in enumerate(row, 1):
        cell = worksheet.cell(row=row_num, column=col_num)
        cell.value = cell_value
        cell.protection = Protection(locked=True)
workbook.save(excelfile)
mail_subject = f'Invoice {mailerID} on {date.today()}'
message = ""
to_email = "[email protected]"
message = EmailMessage(mail_subject, message, settings.EMAIL_HOST_USER, [to_email])
message.attach(f'Invoice {mailerID}.xlsx', excelfile.getvalue(), 'application/vnd.ms-excel')
message.send()
def export_data_to_excel(mailerID) -> None: 
  excelfile = BytesIO()
  workbook = Workbook()
  workbook.remove(workbook.active)
  worksheet = workbook.create_sheet(title='Title Name', index=1)

  bill_queryset =  Bills.objects.filter(cus_id=mailerID, is_exported=False)
  columns = ['Date', 'Reference', 'Confirmation', 'Confirmation', 'Address', 'Service', 'Weight', 'Pricing Zone', 'UspsRate', 'Charges', 'Sur Charges', 'Total Savings', 'Total Charges', 'Customer ID']
  row_num = 1

# Assign the titles for each cell of the header
  for col_num, column_title in enumerate(columns, 1):
    cell = worksheet.cell(row=row_num, column=col_num)
    cell.value = column_title
    cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=False)
    cell.font = Font(bold=True)
# Iterate through all coins
 for _, bill in enumerate(bill_queryset, 1):
    row_num += 1

    # Define the data for each cell in the row
    row = [
        bill.shipDate,
        bill.customerReference,
        bill.customerConfirmation,
        bill.deliveryConfirmation,
        bill.address,
        bill.service,
        bill.weight,
        bill.pricingZone,
        bill.uspsCompRate,
        bill.charges,
        bill.surcharges,
        bill.totalSavings,
        bill.totalCharges,
        bill.customerID,
    ]

    # Assign the data for each cell of the row
    for col_num, cell_value in enumerate(row, 1):
        cell = worksheet.cell(row=row_num, column=col_num)
        cell.value = cell_value
        cell.protection = Protection(locked=True)
workbook.save(excelfile)
mail_subject = f'Invoice {mailerID} on {date.today()}'
message = ""
to_email = "[email protected]"
message = EmailMessage(mail_subject, message, settings.EMAIL_HOST_USER, [to_email])
message.attach(f'Invoice {mailerID}.xlsx', excelfile.getvalue(), 'application/vnd.ms-excel')
message.send()
洛阳烟雨空心柳 2025-02-14 14:38:30

django-tables2可以在此帮助您帮助您,将表创建为类,该表将从数据中馈入,然后您可以将表导出到XLS文档,然后您可以通过电子邮件发送给用户。

参考:

django-tables2 can help you in this, you create your table as Class which will be fed from your data and then you can export the table to XLS document and then you can email to the user.

References:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文