在Python中添加标题 - docx

2024-05-17 05:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python docx创建和编写一个Word文档。

如何使用python docx在文档头中放置文本?

http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png

谢谢


Tags: 文档image文本comhttppngworddocx
3条回答

(关于这个问题已经过时了……)

我在我的项目中使用了一个变通方法,其中我的“客户”希望通过以下方式在不同的页面中使用不同的标题:

  1. 使用python docx和分节符创建文档

  2. 使用两个参数执行word宏文件(.xlsm):(1)fileName=path,docTitle=title,即要插入页脚的文档。

宏文件将打开新创建的文档,并添加已在宏文件中的页眉和页脚。如果页眉和页脚文本需要更改,则需要对其进行修改。

Pyton代码:

wd = win32com.client.Dispatch("Word.Application")
wd.Visible = False
doc = wd.Documents.Open(pathToDOCM) # path here
wd.Run("Main.RunMain",fileName, docTitle) # 2 args
doc.Close()
del wd

VBA代码:

VBA (inside *.xlsm) code:

Sub RunInside()
    Call RunMain("C:\Users\???\dokument.docx", "test")
End Sub

Sub RunMain(wordDocument As String, wordTitle As String)
    ' Create Headers
    Call CreateHeaders(wordDocument, wordTitle)
End Sub

Sub CreateHeaders(wordDocument As String, wordTitle As String)

    Dim i As Integer
    Dim outputName As String

    Dim aDoc As Document
    Dim oApp As Word.Application
    Dim oSec As Word.Section
    Dim oDoc As Word.Document

    Dim hdr1, hdr2 As HeaderFooter
    Dim ftr1, ftr2 As HeaderFooter

    'Create a new document in Word
    Set oApp = New Word.Application
    'Set oDoc = oApp.Documents.Add
    Set oDoc = oApp.Documents.Open(wordDocument)
    'Set aDoc as active document
    Set aDoc = ActiveDocument


    oDoc.BuiltInDocumentProperties("Title") = wordTitle


    For i = 1 To 9:
        Set hdr1 = aDoc.Sections(i).Headers(wdHeaderFooterPrimary)
        Set hdr2 = oDoc.Sections(i).Headers(wdHeaderFooterPrimary)

        Set ftr1 = aDoc.Sections(i).Footers(wdHeaderFooterPrimary)
        Set ftr2 = oDoc.Sections(i).Footers(wdHeaderFooterPrimary)


        If i > 1 Then
            With oDoc.Sections(i).Headers(wdHeaderFooterPrimary)
             .LinkToPrevious = False
            End With

            With oDoc.Sections(i).Footers(wdHeaderFooterPrimary)
             .LinkToPrevious = False
            End With
        End If

        hdr1.Range.Copy
        hdr2.Range.Paste

        ftr1.Range.Copy
        ftr2.Range.Paste

    Next i



    outputName = Left(wordDocument, Len(wordDocument) - 5)
    outputName = outputName + ".pdf"

    oDoc.SaveAs outputName, 17

    oDoc.Close SaveChanges:=wdSaveChanges

    Set oDoc = Nothing
    Set aDoc = Nothing

End Sub

最后备注: 代码循环遍历不同的部分并复制粘贴页眉和页脚。它还将文档保存到*.PDF。

我一直在用它来工作

header = document.sections[0].header
header.add_paragraph('Test Header')

Header是BlockItemContainer的一个子类,它继承了与Document相同的内容编辑功能,例如.add_paragraph()。

很遗憾,此功能尚未实现。链接到的@SamRogers页面是增强建议(aka)的一部分分析页)。不过,@eupharis正在进行实现,因此可能会在一个月左右提供。如果您想跟踪正在进行的拉取请求,请点击此处。https://github.com/python-openxml/python-docx/pull/291

相关问题 更多 >