编程语言
首页 > 编程语言> > 用python实现自动填数生成表格v2.0

用python实现自动填数生成表格v2.0

作者:互联网

这个版本将v1.0中的数据源和填入位置两个excel合并到了一起了。

具体的话请看demo文件:

这里直接给出代码:

from openpyxl import Workbook
from openpyxl import load_workbook
import os
import datetime
import shutil

def now(year=True,month=True,day=True,hour=True,minute=True,second=True):
	def complete(x):
		return '0' + str(x) if x<10 else str(x)
	d = datetime.datetime.now()
	result = ''
	if year:
		result += str(d.year) + '-'
	if month:
		result += complete(d.month) + '-'
	if day:
		result += complete(d.day) + ' '
	if hour:
		result += complete(d.hour) + '-'
	if minute:
		result += complete(d.minute) + '-'
	if second:
		result += complete(d.second) + '-'
	return result[:-1] 

path = os.getcwd()


def run():
	print(now()+' 自动填数生成表格v2.0,开始任务,请稍候...')
	if not os.path.exists(os.getcwd() + '\\' + '模板.xlsx'):
		print('丢失模板.xlsx,请设置好文件再运行...')
		return

	template_name = os.getcwd() + '\\' + '模板.xlsx'

	if not os.path.exists(os.getcwd() + '\\' + '数据.xlsx'):
		print('丢失模板.xlsx,请设置好文件再运行...')
		return

	data_sheet = load_workbook(os.getcwd() + '\\' + '数据.xlsx').active


	lc = []
	for column in range(1,data_sheet.max_column+1):
		lc.append(str(data_sheet.cell(1,column).value).upper())

	outputfolder = 'output ' + now()
	if not os.path.exists(os.getcwd() + '\\' + outputfolder):
		os.mkdir(os.getcwd() + '\\' + outputfolder)
		for row in range(2,data_sheet.max_row+1):
			targetname = os.getcwd() + '\\' + outputfolder + '\\' + str(data_sheet.cell(row,1).value) +'.xlsx'
			shutil.copy(template_name,targetname)
			target = load_workbook(targetname)
			target_sheet = target.active
			for i in range(0,len(lc)):
				target_sheet[lc[i]] = data_sheet.cell(row,i+1).value
			target.save(targetname)


	print(now()+' 任务完成...')
	# except:
	# 	print('您的模板、数据源、填入位置可能填写有误,出现异常了,请好好检查再重新运行...')


run()
print('请输入任意键退出...')
input()

 

标签:load,openpyxl,python,数据源,v2.0,填数,import,True,def
来源: https://blog.csdn.net/sinolzeng/article/details/113973018