繁体   English   中英

Python:将每个 excel 行打印为自己的 ms word 页面

[英]Python: print each excel row as its own ms word page

我有一个包含数千行的 excel 文档,每一行代表一个人的记录。 如何使用 Python 提取每一行并将该信息写入 MS Word 页面?

我的目标是创建一个文档,在其自己的页面上包含每个记录的伪叙述。

您可以将 Excel 文件的内容提取为 Pandas 数据框,然后将数据框作为表格导出到 Word 文档中。 这是实现您的目标的通用语法

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])

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM