Python 根据Excel数据源批量自动填写Excel模板

Python 根据Excel数据源批量填写Excel模板

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import xlwt
from xlutils.copy import copy
import xlrd
import os
import shutil
from datetime import datetime
from xlrd import xldate_as_tuple

#1、打一要修改的excel
#2、再打开另一个excel
#3、把第一个excel里面要修改东西写到第二个表里
#4、把原来的excel删掉,新的excel名改成原来的名字

# 批量修改目标表格模板
xls_name_model1 = "附件1-考评打分表-准备.xls"
# 批量修改数据源表格
xls_khb = "数据源.xlsx"

# 设置数据源行参数

# 设置数据源sheet名称

# 设置数据源表文件夹名称列值



# 该函数中定义:对于没有任何修改的单元格,保持原有格式。
def setOutCell(outSheet, row, col, value):
    """ Change cell value without changing formatting. """

    def _getOutCell(outSheet, colIndex, rowIndex):
        """ HACK: Extract the internal xlwt cell representation. """
        row = outSheet._Worksheet__rows.get(rowIndex)
        if not row: return None

        cell = row._Row__cells.get(colIndex)
        return cell

    # HACK to retain cell style.
    previousCell = _getOutCell(outSheet, col, row)
    # END HACK, PART I

    outSheet.write(row, col, value)

    # HACK, PART II
    if previousCell:
        newCell = _getOutCell(outSheet, col, row)
        if newCell:
            newCell.xf_idx = previousCell.xf_idx
# 开始填写函数
def start():
    book = xlrd.open_workbook(xls_name_model1,formatting_info=True)
    #复制一个excel
    new_book = copy(book)#复制了一份原来的excel
    #通过获取到新的excel里面的sheet页
    sheet = new_book.get_sheet(0)#获取到第一个sheet页

    book_khb = xlrd.open_workbook(xls_khb)
    # “projectList”为sheet名称
    sheet_khb = book_khb.sheet_by_name("projectList") 
    xm_value = []


    for i in range(1,38):
        xm_value.append(sheet_khb.cell_value(i,0))
    #
    for i,xm in enumerate(xm_value):
        m = 2
        value =  sheet_khb.cell_value(i+1,m)

        str_value = datetime(*xldate_as_tuple(value, 0))
        kh_year_value = str_value.year
        kh_month_value =str_value.month
        print(kh_year_value,kh_month_value)

        xm_str = "项目名称:{}工程".format(xm_value[i])
        kh_str = "考评日期:{}年{}月".format(kh_year_value,kh_month_value)

        setOutCell(sheet,1,0,xm_str)#写入excel,第一个值1是行,第二个值0是列
        setOutCell(sheet,1,2,kh_str)#写入excel,第一个值1是行,第二个值2是列
        new_book.save('stu_new.xls')#保存新的excel,保存excel必须使用后缀名是.xls的,不是能是.xlsx的
        os.remove(xls_name_model1)
        os.rename('stu_new.xls',xls_name_model1)
        # os.makedirs(xm_value[i])
        shutil.copyfile(xls_name_model1,xm_value[i] + "/" + xls_name_model1)
   start()
  • 2
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天若有情(爱笑妍)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值