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()

猜你喜欢

转载自blog.csdn.net/weixin_44499757/article/details/86521071