如何使用python docx将csv文件嵌入到Word文档中 [英] How do I embed a csv file into a Word Document with Python docx

查看:174
本文介绍了如何使用python docx将csv文件嵌入到Word文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在打开docx文件,我想在其中嵌入一个csv文件.

I'm opening a docx file and I want to embed into it a csv file.

csv应该显示为图标.

The csv should be displayed as an icon.

我如何在Word文件中设置其ecaxt位置?

How would I set it's ecaxt position in my Word File?

到目前为止,我的代码是:

My code so far is:

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中粘贴特殊动作,并选择了显示为图标"选项.

The next step in each cycle should be to select a csv file and embed it in the word file. It would be the equivalent of a paste special action in Word, with the option Display as Icon selected.

推荐答案

我能够使用pywin32库嵌入csv.

I was able to embed the csv using pywin32 library.

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

这篇关于如何使用python docx将csv文件嵌入到Word文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆