如何使用python Docx将一组标题和段落写到word文档中?

时间:2018-08-07 21:17:20

标签: python-3.x pandas python-docx

我正在阅读有关主题和正文的Outlook新闻。现在,我想将每个主题写为“标题”,并将相关主体写为“段落”。我想循环使用此方法,以获得从Outlook中读取的所有标题和主题。以下是我尝试编写的代码。谁能帮我得到这个吗? 这是代码:

from docx import Document
from docx.shared import Inches
import win32com.client
import pandas as pd


document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True




outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("Newsletters")
inbox = folder.Folders("Inbox")

#inbox= mapi.Folders['Outlook_Mails'].Folders['Inbox']
message = inbox.Items.restrict("[ReceivedTime] > '8/5/2018 12:00 AM'")
message.Sort("[ReceivedTime]", True)
msgs=message.GetFirst()
subjectlist =[]
bodylist =[]

while msgs:
    subjectm=msgs.subject
    bodym=msgs.body
    subjectlist.append(subjectm)
    bodylist.append(bodym)   
    msgs = message.GetNext()


df = pd.DataFrame({'Subject':subjectlist})
df1 = pd.DataFrame({'Mail Body':bodylist})

for i in df,df1:
    document.add_heading(df[i], level=1)
    document.add_paragraph(df1[i], style='IntenseQuote')

document.add_page_break()

document.save('demo.docx')

0 个答案:

没有答案