2015-07-22 49 views
1

我目前正在研究一個需要寫入一個.docx文件用於演示目的的腳本。我使用熊貓來處理腳本中的所有數據計算。我正在尋找使用PyWIN32在word.docx文件的書籤中將一個熊貓數據框寫入表中。數據幀由浮點組成。僞代碼是這樣的。通過pywin32將一個熊貓數據框寫入一個word文檔表

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表格中的標題。

+1

雖然這不是直接回答您的問題,但您可能需要考慮導出爲Excel電子表格(pandas DataFrames有一個[to_excel()](http://pandas.pydata.org/pandas-docs /stable/generated/pandas.DataFrame.to_excel.html)函數)並將結果表插入到文檔中。 – brenns10

+0

你可能無法自動化整個過程(我完全不熟悉PyWin32),但這是使用Windows和GUI應用程序的代價。 – brenns10

+1

使用pywin32時值得注意的是,在許多情況下,它不會讓您將超過2GB的數據加載到內存中,這在使用熊貓時有時會出現問題。這是因爲它是一個32位的Windows進程,默認情況下這些進程通常限制爲2GB。 – firelynx

回答

3

基本上,所有你需要做的是在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,因爲熊貓中的數據幀索引從0開始。

另一個1在行上添加以爲數據幀提供空間列作爲標題。這應該做到這一點!

相關問題