我想将xls文件中的数据显示到HTML表中。我使用openpyxl从xls文件中读取数据。我使用HTML代码使用HTML标签创建表,但我无法使用变量将数据放入表中。我能够打印sheet['A2']
并查看xls文件中的值。我已将此值分配给变量a2
。如何在HTML中打印此变量的值。更具体地说,如何将变量的值放在此标记中:<tr><td class="cell">{%sheet['A2']%}</td> <td class="cell">Cell 1.2</td></tr>
import smtplib
import openpyxl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def py_mail(SUBJECT, BODY, TO, FROM):
"""With this function we send out our html email"""
book =
openpyxl.load_workbook('D:\download\DAILY_PROJECT_REPORT20180420.xlsx')
sheet = book.active
a2 = sheet['A2']
# Record the MIME type text/html.
HTML_BODY = MIMEText(BODY, 'html')
if __name__ == "__main__":
"""Executes if the script is run as main script (for testing purposes)"""
email_content = """
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html title</title>
<style type="text/css" media="screen">
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
border-collapse: collapse;
border-spacing: 5px;
}
</style>
</head>
<body>
<table style="width:70%">
<tr>
<th> PREPAC </th>
<th> TEAM_STATUS </th>
<th> TOTAL </th>
</tr>
<tr><td class="cell">{%sheet['A2']}%</td><td class="cell">Cell 1.2</td>
</tr>
<tr><td class="cell">Cell 2.1</td><td class="cell"></td></tr>
</table>
</body>
"""
py_mail("Test email subject", email_content, TO, FROM)
答案 0 :(得分:0)
一种方法是使用string formatting:
>>> html = """<td>{}</td>"""
>>> s1A2 = 10
>>> print(html.format(s1A2))
<td>10</td>
或使用f-strings:
>>> print(f"""<td>{s1A2}</td>""")
<td>10</td>
>>>
或者在格式字符串中使用带有字典的命名替换字段
>>> data = {'s1A2':10}
>>> html = """<td>{s1A2:}</td>"""
>>> print(html.format(**data))
<td>10</td>
>>>
你的字符串:
s = """<tr><td class="cell">{%sheet['A2']}%</td><td class="cell">Cell 1.2</td>"""
如果使用Python版本3.6+使用f-string:
print(f"""<tr><td class="cell">{sheet['A2']}%</td><td class="cell">Cell 1.2</td>"""
或使用传统格式;
print("""<tr><td class="cell">{}%</td><td class="cell">Cell 1.2</td>""".format(sheet['A2']))