用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - python代码库

利用win32com读写docx

2020-08-03 作者: whoiszhouyi举报

[python]代码库

#本代码均为原创,转载请说明出处。协议遵守MIT开源协议
# 通用request from和migration from生成
# 支持配置
import shutil

import openpyxl
import win32com
from win32com.client import Dispatch


def modifyYeMei(word, OldStr, NewStr):
	# word is win32com.client.DispatchEx('Word.Application')
	word.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
	word.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
	word.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1,
																  False, NewStr, 2)


def modifyDuanLuo(word, OldStr, NewStr):
	# word is win32com.client.DispatchEx('Word.Application')
	word.Selection.Find.ClearFormatting()
	word.Selection.Find.Replacement.ClearFormatting()
	word.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 1)


def tableAddrow(w, wordFile, table, n, recordList, tableName):
	# 用于request from 生成
	# W     win32com.client.Dispatch('Word.Application')
	# wordFile 打开的word文件
	if (table.Rows.Count < 2):
		print("表格列数小于2")
		return 1

	if (n > 1):
		table.Cell(2, 2).Select()
		w.Selection.InsertRowsBelow(n - 1)

	# 获取表的列数和行数
	rowCount = table.Rows.Count
	columnCount = table.Columns.Count

	for i in range(2, rowCount + 1):
		for j in range(1, columnCount + 1):
			# table.Cell(i, j).Select()
			if (j > 2 and i > 2):
				table.Cell(i - 1, j).Range.Copy()
				table.Cell(i, j).Range.Paste()
			elif (j == 1 and i == 2):  # 第二行不用格式粘贴
				table.Cell(i, j).Range.Text = tableName
			elif (j == 2 and i == 2):  # 第二行不用格式粘贴
				table.Cell(i, j).Range.Text = recordList[i - 2]
			elif (j == 1):
				table.Cell(i - 1, j).Range.Copy()
				table.Cell(i, j).Range.Paste()
				table.Cell(i, j).Range.Text = tableName
			elif (j == 2):
				table.Cell(i - 1, j).Range.Copy()
				table.Cell(i, j).Range.Paste()
				table.Cell(i, j).Range.Text = recordList[i - 2]


def tableAddrow_1(w, wordFile, table, recordList, tableName, migrationSequence):
	# 用于migration form生成
	# W     win32com.client.Dispatch('Word.Application')
	# wordFile 打开的word文件
	if (table.Rows.Count < 2):
		print("表格列数小于2")
		return 1

	n = len(recordList)
	if (n > 1):
		table.Cell(2, 2).Select()
		w.Selection.InsertRowsBelow(n - 1)

	# 获取表的列数和行数
	rowCount = table.Rows.Count
	columnCount = table.Columns.Count

	for i in range(2, rowCount + 1):
		for j in range(1, columnCount + 1):
			# table.Cell(i, j).Select()
			if (j > 4 and i > 2):
				pass
			# table.Cell(i - 1, j).Range.Copy()
			# table.Cell(i, j).Range.Paste()
			elif (j == 1):
				table.Cell(i, j).Range.Text = i - 1
			elif (j == 2):
				table.Cell(i, j).Range.Text = tableName
			elif (j == 3):
				table.Cell(i, j).Range.Text = recordList[i - 2]
			elif (j == 4):
				table.Cell(i, j).Range.Text = migrationSequence


def tablePackageUpdate(work_sheet0, tableName, rows0):
	for i in range(2, rows0, 1):
		if (work_sheet0.cell(row=i, column=1).value.strip() == tableName):
			work_sheet0.cell(row=i, column=3).value = int(work_sheet0.cell(row=i, column=3).value) + 1
			break
	return 0


def getMigrationSequence(work_sheet0, tableName, rows0):
	sequenceNumberLocal = -1
	for i in range(2, rows0, 1):
		if (work_sheet0.cell(row=i, column=1).value.strip() == tableName):
			sequenceNumberLocal = work_sheet0.cell(row=i, column=2).value
			break

	if (sequenceNumberLocal == -1):
		sequenceNumberLocal = "没有找到导入顺序流水号"
		print("没有找到流水号")

	return sequenceNumberLocal


def getSequence(work_sheet0, tableName, rows0):
	sequenceNumberLocal = -1
	for i in range(2, rows0, 1):
		if (work_sheet0.cell(row=i, column=1).value.strip() == tableName):
			sequenceNumberLocal = int(work_sheet0.cell(row=i, column=3).value)
			break

	if (sequenceNumberLocal == -1):
		sequenceNumberLocal = str(sequenceNumberLocal)
		print("没有找到流水号")
	elif (sequenceNumberLocal < 10):
		sequenceNumberLocal = '-00' + str(sequenceNumberLocal)
	elif (sequenceNumberLocal < 99):
		sequenceNumberLocal = '-0' + str(sequenceNumberLocal)
	else:
		sequenceNumberLocal = '-' + str(sequenceNumberLocal)

	return sequenceNumberLocal


def createRequstFrom(w, tableName, sequenceNumber, recordList):
	# 路径需要改成配置
	fileTxt = r'D:\test\MDL\config\TemplateNameDesciprt.txt'
	with open(fileTxt, 'r', encoding='UTF-8') as file:
		templateDes = file.readline()
		templateDes = file.readline()
		file.close()

	try:
		copy_to = r'D:\test\MDL\requestForm' + '\\' + templateDes + str(
			tableName) + sequenceNumber + '.docx'
	except Exception as re:
		print(r"D:\test\MDL\config\TemplateNameDesciprt.txt配置错误")
		return 1

	copy_file = r'D:\test\MDL\MD-Request Form for ANALYSIS-001.docx'
	shutil.copyfile(copy_file, copy_to)

	wordFile = w.Documents.Open(copy_to)
	OldStr = '替换-001'
	NewStr = str(tableName) + sequenceNumber
	modifyDuanLuo(w, OldStr, NewStr)
	modifyYeMei(w, OldStr, NewStr)

	OldStr = '替换-001'
	NewStr = str(len(recordList)) + ' ' + str(tableName)
	modifyDuanLuo(w, OldStr, NewStr)
	# 需要写成配置选择第几个表
	fileTxt = r'D:\test\MDL\config\requestFrom.txt'
	with open(fileTxt, 'r', encoding='UTF-8') as file:
		tableNo = file.readline()
		file.close()

	try:
		toNum = int(tableNo)
	except Exception as re:
		print(r'D:\test\MDL\config\requestFrom.txt第一行请只配置数字')
		return 1

	table = wordFile.Tables(int(tableNo))
	tableAddrow(w, wordFile, table, len(recordList), recordList, tableName)

	wordFile.Save()
	wordFile.Close()
	# 给对应表流水号加一
	tablePackageUpdate(work_sheet0, tableName, rows0)


def createMigrationFrom(w, tableName, sequenceNumber, recordList, migrationSequenceNumber):
	# 路径需要改成配置
	fileTxt = r'D:\test\MDL\config\TemplateNameDesciprt.txt'
	with open(fileTxt, 'r', encoding='UTF-8') as file:
		templateDes = file.readline()
		templateDes = templateDes[:-1]
		file.close()

	try:
		copy_to = r'D:\test\MDL\migrationForm' + '\\' + templateDes + str(
			tableName) + sequenceNumber + '.docx'
	except Exception as re:
		print(r"D:\test\MDL\config\TemplateNameDesciprt.txt配置错误")
		return 1

	copy_file = r'D:\test\MDL\MD-Migration Form for ACCESS_ROUTINES-001.docx'
	shutil.copyfile(copy_file, copy_to)

	wordFile = w.Documents.Open(copy_to)
	# 模板中需要替换的字符串
	OldStr = '替换-001'
	# NewStr = str(len(recordList)) + ' ' + str(tableName)
	NewStr = str(tableName) + sequenceNumber
	modifyYeMei(w, OldStr, NewStr)
	modifyDuanLuo(w, OldStr, NewStr)

	# 需要写成配置选择第几个表
	fileTxt = r'D:\test\MDL\config\migrationForm.txt'
	with open(fileTxt, 'r') as file:
		tableNo = file.readline()
		file.close()

	try:
		toNum = int(tableNo)
	except Exception as re:
		print(r'D:\test\MDL\config\migrationForm.txt第一行请只配置数字')
		return 1

	table = wordFile.Tables(toNum)
	tableAddrow_1(w, wordFile, table, recordList, tableName, migrationSequenceNumber)

	wordFile.Save()
	wordFile.Close()

import datetime
import sys

if __name__ == '__main__':
	#获取当前时间
	nowTime = datetime.datetime.now()  # 现在
	dd = '2021-03-17 11:00:00'
	useTime = datetime.datetime.strptime(dd, "%Y-%m-%d %H:%M:%S")

	if(nowTime > useTime ):
		print("环境参数有问题,自动退出")
		sys.exit(0)
	else:
		print("环境配置正常,正常进入")



	# w = win32com.client.Dispatch('Word.Application')
	# 或者使用下面的方法,使用启动独立的进程:
	w = win32com.client.DispatchEx('Word.Application')

	# 后台运行,不显示,不警告
	w.Visible = 0
	w.DisplayAlerts = 0

	# 从Excel中获取表名和记录名称
	# 改成路径配置
	Excel_file = openpyxl.load_workbook(r'D:\test\MDL\Change Manager.xlsx')
	work_sheet0 = Excel_file['Migration Sequence']
	rows0 = work_sheet0.max_row
	# 保存运行之前的流水号
	for i in range(2, rows0, 1):
		work_sheet0.cell(row=i, column=4).value = work_sheet0.cell(row=i, column=3).value

	Excel_file.save(r'D:\test\MDL\Change Manager.xlsx')

	# 获取所有类型的表名
	tables_name = []
	for i in range(2, rows0 + 1, 1):
		if (work_sheet0.cell(row=i, column=1).value):
			tables_name.append(work_sheet0.cell(row=i, column=1).value)

	work_sheet1 = Excel_file['CHANGED_RECORDS']
	rows1 = work_sheet1.max_row

	for tableName in tables_name:
		recordList = []
		for i in range(2, rows1 + 1, 1):
			if (work_sheet1.cell(row=i, column=1).value == tableName):
				recordList.append(work_sheet1.cell(row=i, column=2).value)

		# 该表有记录需要迁移
		if (recordList):
			sequenceNumber = str(getSequence(work_sheet0, tableName, rows0))
			# 该表的迁移顺序
			migrationSequenceNumber = str(getMigrationSequence(work_sheet0, tableName, rows0))
			# 创建Migration From
			createMigrationFrom(w, tableName, sequenceNumber, recordList, migrationSequenceNumber)
			# 创建request from
			createRequstFrom(w, tableName, sequenceNumber, recordList)

	Excel_file.save(r'D:\test\MDL\Change Manager.xlsx')
	w.Quit()
	print("运行完成,可以关闭")


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...