[英]Writing a pandas dataframe to a word document table via pywin32
我目前正在編寫一個腳本,需要寫入.docx文件以進行演示。 我使用pandas來處理腳本中的所有數據計算。 我期待使用PyWIN32將一個pandas數據幀寫入word.docx文件中的書簽的表中。 數據框由浮點數組成。 psuedo代碼是這樣的。
frame = DataFrame(np.arange(28).reshape((4,7)), columns=['Text1',...'Text7'])
用pywin32導入...
wordApp = win32.gencache.EnsureDispatch('Word.Application')
wordApp.Visible = False
doc = wordApp.Documents.Open(os.getcwd()+'\\template.docx')
rng = doc.Bookmarks("PUTTABLEHERE").Range
rng.InsertTable.here
現在我想在這個書簽上創建一個表格。 表格的大小應由數據框決定。 我還希望列標題是Word表格中的標題。
基本上,您需要做的就是在word中創建一個表,並從數據框的相應值中填充每個單元格的值
# data frame
df= DataFrame(np.arange(28).reshape((4,7)), columns=['Text1',...'Text7'])
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])
請注意, Table.Cell(row+1+1,col+1)
在這里添加了兩個。 原因是因為Microsoft Word中的表從1開始索引。因此,必須將行和列添加1,因為pandas中的數據幀索引從0開始。
在行添加另一個1以為數據框列提供空間作為標題。 應該這樣做!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.