2015-04-14 175 views
-1

我正在打開一個docx文件,並且想將其嵌入到一個csv文件中。如何使用Python docx將csv文件嵌入到Word文檔中

csv應顯示爲圖標。

我該如何在我的Word文件中設置它的ecaxt位置?

到目前爲止我的代碼是:

from Tkinter import Tk 
from tkFileDialog import askopenfilename 
import csv 
from docx import Document 
import datetime 


today = datetime.date.today() 

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing 
#filename = askopenfilename(title='Specify data csv file',filetypes=[('text files', '.csv')]) # show an "Open" dialog box and return the path to the selected file 
filename='C:/Documents and Settings/K/My Documents/LiClipse Workspace/WO_templates/WO_templates/data.csv' 

with open(filename, 'r') as csvfile: 
    data_csv = csv.reader(csvfile, delimiter=',') 
    for row in data_csv: 
     if row[3]<>'Name': 
      document = Document('2G_Template.docx') 

      for table in document.tables: 
       for _cell in table._cells: 
        for paragraph in _cell.paragraphs: 
         if '%DATE%' in paragraph.text: 
          paragraph.text=str(today.day)+'/'+str(today.month)+'/'+str(today.year) 
         if 'R%RR%' in paragraph.text: 
          paragraph.text='R'+row[0]      
         if '%DESC%' in paragraph.text: 
          paragraph.text=row[1] 

      for paragraph in document.paragraphs: 
       if '%DEL_PLAN%' in paragraph.text: 
        paragraph.text='Deletion PLan: '+row[2] 



      document.save(row[3]+'.docx') 

每個循環中的下一個步驟應該是選擇一個CSV文件,並將其嵌入到Word文件。這將相當於Word中的粘貼特殊操作,並且選中「顯示爲圖標」選項。

+0

請[編輯您的帖子(http://stackoverflow.com/posts/29628625/edit),包括([你迄今編寫的代碼] http://stackoverflow.com/help/mcve )。 – GoBusto

回答

0

我能夠使用pywin32庫嵌入csv。

import win32com.client as win32 
. 
. 
. 
word = win32.gencache.EnsureDispatch('Word.Application') 
doc=word.Documents.Open(doc_path) 
word.Visible = False 
. 
. 
. 
doc.InlineShapes.AddOLEObject(FileName=doc_path3,DisplayAsIcon=1,Range=range1,IconLabel="CSV",IconFileName=doc_path4) 

word.ActiveDocument.SaveAs(doc_path2) 
doc.Close() 
相關問題