【问题标题】:Editing a .odt File using python使用 python 编辑 .odt 文件
【发布时间】:2015-06-02 12:43:46
【问题描述】:

首先我必须说我对编程非常陌生(总共不到一周的经验)。我开始编写一个程序来生成一系列 .odt 模板的文档。我想使用带有特定关键字的模板,比如“X1234X”等等。这将被程序生成的值替换。每个文档都有点不同,值是通过提示输入和计算的(日期和其他内容)

到目前为止,我编写了大部分代码,但自从 2 天以来,我一直在这个问题上陷入困境。我使用 ezodf 模块从模板生成一个新文档(具有不同的文件名),但我被困在如何编辑内容上。 我用谷歌搜索但空无一物,希望这里有人可以提供帮助。我尝试阅读文档,但我必须说实话......这有点难以理解。我不熟悉“俚语”

谢谢

PS:ezodf 方法会很棒,但任何其他方法也可以。程序不一定要漂亮,只要能工作(这样我可以少工作^_^)

【问题讨论】:

    标签: python-3.x editing odt


    【解决方案1】:

    嗯,我想通了。 nd 完成了程序。我使用 ezodf 创建文件,然后使用 zipfile 提取和编辑 content.xml,然后通过来自here 的漂亮 >def thingy

    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)
    

    【讨论】:

      猜你喜欢
      • 2011-02-14
      • 2023-04-04
      • 2021-09-28
      • 2015-01-31
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      相关资源
      最近更新 更多