自制excel模板,然后用openpyxl写入数据

1. 前提条件必须自己制作一个excel的模板如下(可以自己随便设计)

template1.xlsx.png

2. 小小的一个demo-examples

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

import shutil
import openpyxl
import datetime


def create_new_excel(tempalte_excel_path, new_excel_path):
    shutil.copy(tempalte_excel_path, new_excel_path)


def update_new_excel(new_excel_path, data):
    wb = openpyxl.load_workbook(filename=new_excel_path)
    ws = wb.worksheets[0]

    ws["A1"] = data["title"]

    row = 4
    for item in data["items"]:
        ws["A%s" % row] = item[0]
        ws["B%s" % row] = item[1]
        ws["C%s" % row] = item[2]
        ws["D%s" % row] = item[3]
        ws["E%s" % row] = item[4]
        ws["F%s" % row] = item[5]

        row += 1

    wb.save(new_excel_path)


def main():
    template_excel_path = "./template1.xlsx"
    new_excel_path = "./02_test_openpyxl_excel.xlsx"
    create_new_excel(template_excel_path, new_excel_path)

    data = {
        "title": "Test Openpyxl Excel Demo Examples",
        "items": [
            [1001, "丁三", "运维工程师", "A", "15k", datetime.datetime.now().date() - datetime.timedelta(days=730)],
            [1002, "王五", "ISO工程师", "A", "15k", datetime.datetime.now().date() - datetime.timedelta(days=740)],
            [1003, "张三", "Golang后端工程师", "A", "15k", datetime.datetime.now().date() - datetime.timedelta(days=1200)],
        ]
    }
    update_new_excel(new_excel_path, data)


if __name__ == '__main__':
    main()

3. 结果

结果.png

你可能感兴趣的:(自制excel模板,然后用openpyxl写入数据)