Oledtrix
Oledtrix

Reputation: 57

How to include an Excel range in a string?

I've been trying to write an algorithm that would help me answer emails more efficiently, and I hit an impasse when I got to the formatting of the response.

So, the response is a pre-structured text and I want to embed an Excel range in the middle of it as a table, to then copy it to the clipboard and paste it, then send it. Basically, the reply should look as follows:

I've tried using Pandas.Dataframe.to_string() for that purpose, but the formatting is very disorganized and unpleasant to look at. I know how you can copy an Excel range to an email and it works well, so I was wondering if there's any way one can embed an Excel range to a string, to then copy it to the clipboard.

Here's a snippet of code related to the response setup:

response_string = response_string + response_template[:243] + df.to_string(index=False) + "\n\n" + response_template[243:]

Maybe I'm doing something wrong by using a regular string variable for the response?

Thanks in advance!

Cheers.

Upvotes: 1

Views: 150

Answers (1)

Cheche
Cheche

Reputation: 1516

I'd suggest using jinja templates for that.

from jinja2 import Environment, PackageLoader, select_autoescape

def render_email(df):
    env = Environment(
        loader=PackageLoader("app"),  # Choose another loader if convenient
        autoescape=select_autoescape()
    )
    template = env.get_template("template.html")
    return template.render(dataframe=df)

Being your template file template.html:

The data you requested is:
{% for key, value in dataframe.iterrows() %}
{{key}}: {{value}} {# You can choose here how to iterate/display your data #}
{% endfor %}
Thank you for contacting us

How you iterate your dataframe depends on the data it contains.

Upvotes: 1

Related Questions