代码之家  ›  专栏  ›  技术社区  ›  Khanh Le

编辑文档Python docx标题中的内容

  •  3
  • Khanh Le  · 技术社区  · 8 年前

    我正在尝试查找并替换中的文本 标题中的文本框 文件的。但在搜索了一段时间后,似乎无法通过python docx访问标题或“浮动”文本框中的内容(我阅读了这篇文章) here )

    2 回复  |  直到 8 年前
        1
  •  5
  •   Khanh Le    8 年前

    template.docx 文件,我想在 标题中的文本框

    1. 模板.docx template.zip
    2. template
    3. header<number>.xml 文件位于 /template/word/ 文件夹
    4. /template 文件夹返回到 模板.zip
    5. 模板.zip 模板.docx

    import os
    import shutil
    import zipfile
    
    WORKING_DIR = os.getcwd()
    TEMP_DOCX = os.path.join(WORKING_DIR, "template.docx")
    TEMP_ZIP = os.path.join(WORKING_DIR, "template.zip")
    TEMP_FOLDER = os.path.join(WORKING_DIR, "template")
    
    # remove old zip file or folder template
    if os.path.exists(TEMP_ZIP):
        os.remove(TEMP_ZIP)
    if os.path.exists(TEMP_FOLDER):
        shutil.rmtree(TEMP_FOLDER)
    
    # reformat template.docx's extension
    os.rename(TEMP_DOCX, TEMP_ZIP)
    
    # unzip file zip to specific folder
    with zipfile.ZipFile(TEMP_ZIP, 'r') as z:
        z.extractall(TEMP_FOLDER)
    
    # change header xml file
    header_xml = os.path.join(TEMP_FOLDER, "word", "header1.xml")
    xmlstring = open(header_xml, 'r', encoding='utf-8').read()
    xmlstring = xmlstring.replace("#TXTB1", "Hello World!")
    with open(header_xml, "wb") as f:
        f.write(xmlstring.encode("UTF-8"))
    
    # zip temp folder to zip file
    os.remove(TEMP_ZIP)
    shutil.make_archive(TEMP_ZIP.replace(".zip", ""), 'zip', TEMP_FOLDER)
    
    # rename zip file to docx
    os.rename(TEMP_ZIP, TEMP_DOCX)
    shutil.rmtree(TEMP_FOLDER)
    
        2
  •  1
  •   patb    8 年前

    另一种方法是在内存中:

    def docx_setup_header(doc_sio_1, new_title):
        """
        Returns a StringIO having replaced #TITLE# placeholder in document header with new_title
        :param doc_sio_1:  A StringIO instance of the docx document.
        :param new_title:  The new title to be inserted into header, replacing #TITLE# placeholder
        :return: A new StringIO instance, with modified document.
        """
    
        HEADER_PATH = 'word/header1.xml'
    
        doc_zip_1 = zipfile.ZipFile(doc_sio_1, 'r')
        header = doc_zip_1.read(HEADER_PATH)
        header = header.replace("#TITLE#", new_title)
    
        doc_sio_2 = StringIO.StringIO()
        doc_zip_2 = zipfile.ZipFile(doc_sio_2, 'w')
        for item in doc_zip_1.infolist():
            content = doc_zip_1.read(item.filename)
            if item.filename == HEADER_PATH:
                doc_zip_2.writestr(HEADER_PATH, header, zipfile.ZIP_DEFLATED)
            else:
                doc_zip_2.writestr(item, content)
    
        doc_zip_1.close()
        doc_zip_2.close()
    
        return doc_sio_2