2016-11-14 337 views
2

我正在創建使用Pandas DataFrame的Python生成報告。目前我正在使用DataFrame.to_string()方法。但是,這會以字符串形式寫入文件。有一種方法可以讓我在保持表格形式的同時實現此目的,以便使用表格格式。將Python Pandas DataFrame寫入Word文檔

代碼:

SEMorgkeys = client.domain_organic(url, database = "us", display_limit = 10, export_columns=["Ph,Pp,Pd,Nq,Cp,Ur,Tr"]) 
org_df = pd.DataFrame(SEMorgkeys) 

f = open(name, 'w') 
f.write("\nOrganic:\n") 
f.write(org_df.to_string(index=False,justify="left")) 
f.close() 

當前打印輸出(如字符串):

CPC Keyword      Position Difference Previous Position Search Volume Traffic (%) Url            
75.92  small business factoring 0     1     210   11.69  https://www..com/small-business-f... 
80.19    factoring company 0     8    1600   5.72  https://www..com/factoring-vs-ban... 
+0

它可能會更容易將數據寫入到.csv,然後複製/粘貼或從Excel導入表到Word –

+0

爲單一的表是的,我會同意。但是,我正在循環大約12個URL,每個循環約有6個DataFrame。我真的不想爲72個表創建一個.csv。 – spriore

+0

您可以添加一些附加信息。你是否試圖在MSWord中將數據框寫爲格式化的表格,或者只是使用'.to_string'方法將格式化的文本添加到行中? – James

回答

6

您可以使用python-docx庫編寫表直入一個.docx文件。

如果您使用的是康達或使用蟒蛇安裝Python,您可以運行命令行命令:

conda install python-docx --channel conda-forge 

或者到點子命令行安裝:

pip install python-docx 

後我們可以使用它來打開文件,添加一個表格,然後用數據幀數據填充表格的單元格文本。

import docx 
import pandas as pd 

# i am not sure how you are getting your data, but you said it is a 
# pandas data frame 
df = pd.DataFrame(data) 

# open an existing document 
doc = docx.Document('./test.docx') 

# add a table to the end and create a reference variable 
# extra row is so we can add the header row 
t = doc.add_table(df.shape[0]+1, df.shape[1]) 

# add the header rows. 
for j in range(df.shape[-1]): 
    t.cell(0,j).text = df.columns[j] 

# add the rest of the data frame 
for i in range(df.shape[0]): 
    for j in range(df.shape[-1]): 
     t.cell(i+1,j).text = str(df.values[i,j]) 

# save the doc 
doc.save('./test.docx') 
+0

什麼是'df = pd.DataFrame(數據)中的數據' ' – pyd

+0

@pyd'data'是數據源(您輸入的內容是什麼)爲您的'DataFrame' – spriore

+0

有沒有辦法在表?代碼可以工作,但我認爲我的報告看起來會更好一些,我的熊貓數據框的邊界被寫入我的Word文檔。謝謝! :) – HenryHub