使用python编辑.odt文件

伊诺索菲特

首先,我必须说我对编程非常陌生(总共不到一周的经验)。我着手编写一个程序,该程序生成一系列.odt模板的文档。我想使用带有特定关键字的模板,让我们说“ X1234X”,依此类推。然后将其替换为从程序生成的值。每个文档略有不同,并且通过提示输入和计算值(日期和其他内容)

到目前为止,我已经编写了大多数代码,但是由于这个问题我已经停滞了两天了。我使用ezodf模块从模板生成一个新文档(使用不同的文件名),但是我仍然坚持如何编辑内容。我用力地搜寻了一下,但空荡荡的希望这里的人能帮上忙。我尝试阅读文档,但我必须诚实...这有点难以理解。我不熟悉“ s语”

谢谢

PS:ezodf方法会很棒,但是其他任何方法也可以。该程序不必很漂亮,它只需要工作(这样我就可以少工作^ _ ^)

伊诺索菲特

好吧,我想通了。nd完成程序。我使用ezodf创建文件,然后使用zipfile提取并编辑content.xml,然后通过一个不错的> def somethingy <从这里重新打包了整个内容我试图把etree弄乱了...但是我想不起来...

from ezodf import newdoc
import os
import zipfile
import tempfile

for s in temp2:
input2 = s
input2 = str(s)
input1 = cname[0]
file1 = '.odt'
namef = input2 + input1 + file1
odt = newdoc(doctype='odt', filename=namef, template='template.odt')
odt.save()
a = zipfile.ZipFile('template.odt')
content = a.read('content.xml')
content = str(content.decode(encoding='utf8'))
content = str.replace(content,"XXDATEXX", input2)
content = str.replace(content, 'XXNAMEXX', input1)



def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    # create a temp copy of the archive without filename
    with zipfile.ZipFile(zipname, 'r') as zin:
        with zipfile.ZipFile(tmpname, 'w') as zout:
            zout.comment = zin.comment # preserve the comment
            for item in zin.infolist():
                if item.filename != filename:
                    zout.writestr(item, zin.read(item.filename))

    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    # now add filename with its new data
    with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
        zf.writestr(filename, data)

updateZip(namef, 'content.xml', content)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章