python-docx 标题_使用Python docx放置标题

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

我在我的项目中使用了一个变通方法,其中我的“客户”希望通过以下方式在不同的页面中使用不同的标题:使用python docx和分节符创建文档

使用两个参数执行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。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值