from loguru import logger import win32com.client as win32 import os import datetime import time from docx import Document
# 插入表格 definsert_tables(sourceDoc,targetDoc): # 创建word应用程序对象 word_app = win32.Dispatch("Word.Application") # 打开要插入表格的word文档 doc = word_app.Documents.Open('D:/a.docx') # time.sleep(5) # VBA字符串只能255个字符,所以拆成两段拼接一下 vba_code_part1 = ''' Sub InsertTables() Dim sourceDoc As Document Dim targetDoc As Document Dim sourceTable As Table Dim foundRange As Range Dim deleteRange As Range Dim tableIndex As Integer ''' vba_code_part2 = ''' Set sourceDoc = Documents.Open("{}") Set targetDoc = Documents.Open("{}") '''.format(sourceDoc,targetDoc) vba_code_part3 = ''' tableIndex = 1 ' 在源文件中查找每個“【插入表格】” For Each sourceTable In sourceDoc.Tables Set foundRange = targetDoc.Content With foundRange.Find .Text = "【插入表格】" .Execute End With ''' vba_code_part4 = ''' If foundRange.Find.Found Then ' 刪除段落 Set deleteRange = foundRange.Paragraphs(1).Range deleteRange.Delete ' 复制表格 sourceTable.Range.Copy foundRange.Paste ''' vba_code_part5 = ''' Else Exit Sub End If ' 更新表格索引 tableIndex = tableIndex + 1 Next sourceTable ' 关闭源文件和目标文件 sourceDoc.Close targetDoc.Close End Sub
for table in doc.tables: for row in table.rows: for cell in row.cells: paragraphs = cell.paragraphs for paragraph in paragraphs: for run in paragraph.runs: if run.text.endswith(";"): modified_text = run.text[:-1] + "。"# 将分号改为句号 run.text = modified_text
doc.save(filename)
if __name__ == '__main__': # pass # 创建日志对象 FileLog = 'D:/workspace/weeklyNewspaper/log/log{}.log'.format(datetime.date.today()) logger.add(FileLog,rotation="500MB", encoding="utf-8", enqueue=True) logger.info('***开始处理各总部表格***') footnotes = [] fontindextext = [] path = 'D:/aidownload/gongsizhoubao/{}'.format(datetime.datetime.today().date()) logger.info('遍历文件夹下的文件') for i in os.listdir(path): if i != '公司周报{}.docx'.format(datetime.datetime.today().date()) : logger.info(path + '/' +i) insert_tables(path + '/' +i,path + '/公司周报{}.docx'.format(datetime.datetime.today().date())) logger.info('--该文件已处理') time.sleep(5) logger.info('遍历各总部表格单元格行尾,若以“;”结尾则修改为“。”') modify_word_table(path + '/公司周报{}.docx'.format(datetime.datetime.today().date())) logger.info('***各总部表格处理结束***')