[英]Python: print each excel row as its own ms word page
I've got an excel document with thousands of rows, each row represents a person's record.我有一个包含数千行的 excel 文档,每一行代表一个人的记录。 How can I use Python to extract each row and write that information into an MS Word page?
如何使用 Python 提取每一行并将该信息写入 MS Word 页面?
My goal is to create a doc containing a pseudo-narrative of each record on its own page.我的目标是创建一个文档,在其自己的页面上包含每个记录的伪叙述。
You can extract the content of the Excel file as a Pandas Data Frame and then export the Data Frame into Word Document as a table.您可以将 Excel 文件的内容提取为 Pandas 数据框,然后将数据框作为表格导出到 Word 文档中。 This is the generic syntax to achieve your objective
这是实现您的目标的通用语法
import pandas as pd
xls_file = pd.ExcelFile('../data/example.xls')
df = xls_file.parse('Sheet1')
#Needs PyWin32
wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range
# creating Table
# add one more row in table at word because you want to add column names as header
Table=rng.Tables.Add(rng,NumRows=df.shape[0]+1,NumColumns=df.shape[1])
for col in range(df.shape[1]):
# Writing column names
Table.Cell(1,col+1).Range.Text=str(df.columns[col])
for row in range(df.shape[0]):
# writing each value of data frame
Table.Cell(row+1+1,col+1).Range.Text=str(df.iloc[row,col])
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.