不同格式的word文档合并为一个文件。

问题:

文件汇编,需要将70多个文件汇编成一个到一个文件里。最终汇编的方式是用word--插入--对象--文件中的文字。

但是由于原始文件有的设置了自动编号。插入后在合并后的文档上继续编号导致混乱。有的没有设置标题样式,提取不出来目录。

最终汇总的时候,需要清楚自动编号的域,已经生成的编号转换成文字,统一设置标题格式.

同一个段里,字体还不一样,需要清除Word的标题样式保留字体格式。

解决方式:

开始享用python+docx库解决。但是docx库在原始文档没有style的情况下,无论如何添加不进去。

if match(run.text,"第*章*"): #匹配模式为问号,及匹配一个任意字符document.add_heading("",level=1)paragraph.style = document.styles['heading 1']

这样的总是出错,因为heading不存在,查了官方文档,说word默认有很多样式,但是你不起用的话,文档里是没有这个样式的。docx文档里也没说怎么解决。

"no style with name 'Heading 1'"

换解决思路:

用 win32com 操作

里面用到一句

ActiveDocument.ConvertNumbersToText

在VBA里运行没有问题,但是win32调用也出错。

查找过程中查到一个用WIN32直接运行宏命令的方式,算球,全部代码写在vba里,python循环目录和重命名就好。这样的好处是,python只负责循环和重命名,有需求直接修改vba.bas就好了,宏兼容性最高。

于是代码如下:

import os
import globfrom win32com.client import constantsfrom win32com.client import Dispatch #需要安装的是pypiwin32模块App=Dispatch('Word.Application')
App.Visible=0def addmaco(file):App.DisplayAlerts = 0doc = App.Documents.Open(file)#导入宏代码#通过文档实例,获取VBProject的组件,其中VBComponents中的参数至关重要,因为ThisDocument表示该文档,也就是说所有这篇生成文档的操作在该组件中都可以捕获#到,那么就可以在里面创建Document_Open函数来监控文档被打开docCode = doc.VBProject.VBComponents("ThisDocument").CodeModulemacro = ""#vba.bas为宏文件,需要导入到ThisDocument,ThisDocument即对应word下,按Alt+F11,调出vba窗口,该文档下的Microsoft Word对象下的ThisDocument。string=open("vba.bas", encoding='utf-8')macro=string.read()docCode.AddFromString(macro)#doc.Save()   #添加宏这里不能保存,因为word无法保存为不含宏的文件.但是添加宏以后就可以运行了。python里就是用到这个功能def DelMacro(file): #添加宏App.DisplayAlerts = 0doc = App.Documents.Open(file) doc.Save() def get_file_path(root_path,file_list,dir_list):#获取该目录下所有的文件名称和目录名称dir_or_files = os.listdir(root_path)for dir_file in dir_or_files:#获取目录或者文件的路径dir_file_path = os.path.join(root_path,dir_file)#判断该路径为文件还是路径if os.path.isdir(dir_file_path):dir_list.append(dir_file_path)#递归获取所有文件和目录的路径get_file_path(dir_file_path,file_list,dir_list)else:file_list.append(dir_file_path)root_path = r"D:\企业制度"file_list = []
dir_list = []
path='d:/'
get_file_path(root_path,file_list,dir_list)for dirlst in dir_list:path=dirlstprint(path)preName="" #二级目录dir=(dirlst.split("\\"))                            if (len(dir))>2:preName=(dir[2])old_names = os.listdir(path)  #取路径下的文件名,生成列表for old_name in old_names:      #遍历列表下的文件名if os.path.isfile(path + "\\" +old_name): #防止文件夹加上.pdf后缀,先判断是否是文件,必须带路径if old_name.endswith('.doc') or old_name.endswith('.docx'):file=path + "\\" +old_nameprint("打开:"+file)doc = App.Documents.Open(file)addmaco(file)App.Application.Run("numTotext")filename=App.ActiveDocument.Sentences(1).Text.replace('\r','') #删除字符串里的回车符if filename=="": #如果第一行为空,取第二行filename=App.ActiveDocument.Sentences(2).Text.replace('\r','')filename=filename.replace('\t','')filename=filename.replace('\t','')#filenamePara=str(App.ActiveDocument.Paragraphs(1)).replace('\r','')#filenamePara=filenamePara.replace('\t','')#print(filenamePara)print(filename)       newpath="d:\\企业制度统一格式\\"+preNameNewfile=newpath+"\\"+preName+"_"+str(filename)print(Newfile)doc.SaveAs(Newfile,16) #将所有doc,docx都统一保存为docx,后面带16doc.Close()
App.Quit()

vba.bas文件如下

Sub numTotext()'数字转文本 '仅list是 ActiveDocument.range.listformat.ConvertNumbersToTextActiveDocument.ConvertNumbersToText '自动编号的数字会变成文本,但是域还在'删除第一行'单位名称'Selection.HomeKey Unit:=wdStorySelection.Find.ClearFormattingSelection.Find.Replacement.ClearFormattingWith Selection.Find.Text = "单位名称^p" '包括换行.Replacement.Text = "".Forward = True.Wrap = wdFindAsk.Format = False.MatchCase = False.MatchWholeWord = False.MatchByte = True.MatchWildcards = False.MatchSoundsLike = False.MatchAllWordForms = False.Execute Replace:=wdReplaceOneEnd WithSelection.HomeKey Unit:=wdStory '回到首行Dim searchStrsearchStr = Chr(13)If (InStr(ActiveDocument.Paragraphs(1).Range.Text, searchStr) = 1) Then     '如果第一行是回车,删除Selection.Range.DeleteEnd If'去除底纹Selection.WholeStory Options.DefaultHighlightColorIndex = wdNoHighlightSelection.Range.HighlightColorIndex = wdNoHighlight
'Sub 清除Word的标题样式保留字体格式()Dim para As ParagraphDim fnt As FontDim pfmt As VariantDim lineup1 As VariantDim lineup2 As VariantDim linedo1 As VariantDim linedo2 As VariantDim fntName As VariantDim fntsize As VariantDim shSj As VariantDim lineSpace As VariantDim lnSpcrule As VariantDim alnMent As VariantWith ActiveDocument.Styles("正文").Font.NameFarEast = "仿宋_GB2312".NameAscii = "Calibri".NameOther = "Calibri".Name = "Calibri".Size = 16End With'无标记With ActiveWindow.View.RevisionsFilter.Markup = wdRevisionsMarkupNone.View = wdRevisionsViewFinalEnd With'接受修订ActiveDocument.AcceptAllRevisionsActiveDocument.TrackRevisions = FalseFor Each para In ActiveDocument.ParagraphsWith para'If .Style <> ActiveDocument.Styles("正文") 不同的文章的正文格式也不一样,所以无论什么格式通通成正文Set fnt = .Range.Font '转换样式之前,先记下来字体Set pfmt = .Style.ParagraphFormatfntName = .Range.Font.Name'MsgBox (.Range.Text)fntsize = .Range.Font.Size                                                    alnMent = .Range.ParagraphFormat.AlignmentshSj = .Range.ParagraphFormat.FirstLineIndent'lineup1 = .Style.ParagraphFormat.LineUnitBefore'lineup2 = .Style.ParagraphFormat.SpaceBefore'linedo1 = .Style.ParagraphFormat.LineUnitAfter'linedo2 = .Style.ParagraphFormat.SpaceAfter'fnt = .Range.Font'pfmt = .Range.ParagraphFormat.LineSpacinglineup1 = .Range.ParagraphFormat.LineUnitBeforelineup2 = .Range.ParagraphFormat.SpaceBeforelinedo = .Range.ParagraphFormat.LineUnitAfterlinedo2 = .Range.ParagraphFormat.SpaceAfterlnSpcrule = .Range.ParagraphFormat.LineSpacingRulelineSpace = .Range.ParagraphFormat.LineSpacing.Style = ActiveDocument.Styles("正文").Range.ListFormat.RemoveNumbers '清除自动编号的代码.Range.Font = fnt.Range.Font.Name = fntName.Range.ParagraphFormat.Alignment = alnMent.Range.Font.Size = fntsize'.Range.ParagraphFormat.LineSpacing = pfmtIf lineSpace < =1 ThenlineSpace = 1End If.Range.ParagraphFormat.LineSpacing = lineSpace'.Range.ParagraphFormat = pfmt.Range.ParagraphFormat.FirstLineIndent = shSj.Range.ParagraphFormat.LineUnitBefore = lineup1.Range.ParagraphFormat.SpaceBefore = lineup2.Range.ParagraphFormat.LineUnitAfter = linedo1.Range.ParagraphFormat.SpaceAfter = linedo2.Range.ParagraphFormat.LineSpacingRule = lnSpcrule.Range.ParagraphFormat.LineSpacing = lineSpace'End IfEnd WithNext'设置页面大小'With ActiveDocument.PageSetup'        .LineNumbering.Active = False'        .Orientation = wdOrientPortrait'        .TopMargin = CentimetersToPoints(3.7)'        .BottomMargin = CentimetersToPoints(3.5)'        .LeftMargin = CentimetersToPoints(2.6)'        .RightMargin = CentimetersToPoints(2.6)'End WithWith ActiveDocument.Styles("标题 1").Font.NameFarEast = "方正小标宋简体".Size = 22End WithWith ActiveDocument.Styles("标题 1").ParagraphFormat.LeftIndent = CentimetersToPoints(0).RightIndent = CentimetersToPoints(0).SpaceBefore = 0.SpaceBeforeAuto = False.SpaceAfter = 0.SpaceAfterAuto = False.LineSpacingRule = wdLineSpaceSingle.Alignment = wdAlignParagraphCenter.WidowControl = True.KeepWithNext = False.KeepTogether = False.PageBreakBefore = FalseEnd WithWith ActiveDocument.Styles("标题 1").AutomaticallyUpdate = False.BaseStyle = "正文".NextParagraphStyle = "标题 2"End WithActiveDocument.Paragraphs(1).Range.Select    Selection.Style = ActiveDocument.Styles("标题 1")For i = 1 To 10 '循环十次,替换空格Selection.WholeStorySelection.Find.ClearFormattingSelection.Find.Replacement.ClearFormattingWith Selection.Find.Text = "章  ".Replacement.Text = "章 ".Execute Replace:=wdReplaceAllEnd WithNext i'添加分页Selection.EndKey Unit:=wdStorySelection.InsertBreak Type:=wdPageBreakEnd Sub

用ptyhon和vba清除Word的标题样式保留字体格式,生成标题目录。相关推荐

  1. 【HTML+CSS网页设计与布局 从入门到精通】第6章-标题h1,h1字体格式的设置方式

    目录 方式1 方式2 方式1 <html> <head><title>演示</title><meta http-equiv="Conte ...

  2. word中如何进行中英文字体格式修改--以及数字上下标

    关于中英文格式修改: WPS会自动跳过中文字体从而达到对字母和数字字体的修改,在word文本页面按[ctrl+A]键全选,然后直接把字体全部调为新罗马字体.然后就会字母和数字是新罗马格式了. > ...

  3. 在Word中为标题样式添加自动编号功能

    转自:http://blog.sina.com.cn/s/blog_6238dcdb0100qz8j.html 摘要: 本文可以帮助你在Office 2007中为Word标题样式添加和设置自动编号功能 ...

  4. word中的标记、分页、批量标题设置、多级列表设置

    一.word标记 1.在word中会有各种各样的标记: (1)→:制表符,使用Tab键可以输出: (2)↓:手动换行符,又叫软回车,使用Shift+Enter可以输出: 注意:软回车文字换行,但不分段 ...

  5. 用VBA在Word文档中每页页眉插入返回文档目录中相应位置的超链接

    [说明]此文中在页眉插入跳转到目录项的超链接的代码几经改进,但改进后并未删除改进之前的代码,是为了有个对比利于学习.如果想节约时间,该步骤可直接查看该部分最后一个代码块. 对于Word长文档,标准做法 ...

  6. VBA操作word生成sql语句

    项目开始一般都是用word保存下数据库的文档 但是从表单一个一个的建表实在是很困难乏味,查查资料 1.可以生成一个html或者xml,检索结构生成sql.但是这个方式也蛮麻烦 2.查到vba可以操作w ...

  7. 利用VBA在Word中排出漂亮的代码

    引言 在学习编程的过程中,常常会使用word来做笔记,下面我将对如何利用word宏来进行代码的排版进行说明 1.工具 我用的是word2007,word2003和word2010操作也差不多 2.基本 ...

  8. vba访问服务器中txt文件,vba读取word内容 vba读取txt文件

    excel vba 读取 word 指定字符 Sub 按钮1()Dim myPath As StringSet Wdapp = CreateObject("Word.Application")Wdap ...

  9. 使用VBA统一word文档表格样式

    在多人协作的word文档中,经常会出现同一性质的内容格式不一致的情况.要快速统一同一性质的内容的格式,最佳实践无疑是使用样式功能.但是对于表格而言,对表格样式的编辑无法做到使表格在页面居中,而且对于标 ...

最新文章

  1. 解决nginx负载均衡的session共享问题
  2. python【蓝桥杯vip练习题库】BASIC-18 矩形面积交(线段交)
  3. 如何系统学习机器学习?
  4. Linux装ntfs后内存不够,Linux_安装Ubuntu后无法使用NTFS硬盘或移动硬盘,  在安装Ubuntu系统后,存在 - phpStudy...
  5. 【转】RAX,eax,ax,ah,al 关系
  6. Python编写caffe代码
  7. 官方 STM32F303ZE Nucleo-144开发板 点亮led
  8. 《深入理解 Spring Cloud 与微服务构建》第五章 Kubernetes
  9. SpringMVC框架----RequestParam注解和RequestBody注解
  10. linux同步Internet时间
  11. 企业系统门户需要哪些模块_人力资源管理系统的主要功能模块有哪些?
  12. 如何在JUnit5中使用Mockito
  13. 2021美团笔试题(第十套)个人解答
  14. H5唤起web地图导航
  15. Observability:Data pipeline:Beats => Redis => Logstash => Elasticsearch
  16. android如何开手机,安卓手机如何打开.data文件?
  17. 我逛遍各大论坛,分享这份大厂招聘总结:涵盖Java岗位95%+真题
  18. 使用asp.net从零开始制作设计网站---转载
  19. 小程序开发系列之基础部分-开发工具
  20. 怎么把图片压缩到30k以内?如何图片压缩到指定大小?

热门文章

  1. 关于Windows 8使用WMP播放音乐时WUDFHost跑CPU和硬盘的问题解决
  2. 掌上医院室内导航导诊系统
  3. PoE供电、集中供电、点对点供电各自的优缺点
  4. ssm教师工作量核算统计系统 毕业设计-附源码162307
  5. 【技术推文】Biome-BGC生态系统模型
  6. golang 调用chatGPT
  7. PMBOK第6版49个过程记忆卡
  8. 请将以太网电缆插曲此计算机台式机,“请将以太网电缆插入此计算机”是什么意思?...
  9. 卡尔曼滤波器(3) -- α−β−γ滤波器(例2)
  10. 浙大远程教育计算机作业2,2016浙大远程教育计算机应用基础作业-2.docx