python练习之openpyxl、docx实现excel取数据导入word中,并且根据word表格自我复制

前言

这是一个人事小姐姐请教的问题,每年都会有类似的统计数据到Excel中,并且将数据填入到word表格中的重复工作出现,所以想实现自动化办公。因为python也只是前两年稍微学习了下的语言,但是小姐姐的请求必须完成!!

一、操作Excel的openpyxl

操作excel部分的代码没遇到什么问题,因为也仅仅需要读取一遍数据。

1、获取文件
from openpyxl import load_workbook

elxFile = r'C:\Users\Administrator\Desktop\test.xlsx'
excel = load_workbook(elxFile)
2、选择Sheet
sheet = excel['Sheet1']
# 最大row
max_row = sheet.max_row
# 最大cow
max_cow = sheet.max_column
3、获取内容
# 从第二行开始执行,最大次数为最大行数 + 1
for row in range(2, max_row + 1):
	#cell两个参数:行数,列数
    print(sheet.cell(row, 1).value)

基本就没了。

二、操作word的docx

docx这个库真的是只能操作docx,doc都不行。
根据小姐姐的需求,需要根据原来存在的表单进行复制,并且另起一页进行粘帖。
这个需求可麻烦了,度娘几乎搜不到类似的需求。

1、复制表格
	# 新增页
    document.add_page_break()
	# 原表格模版
    doc_table = document.tables[0]
    new_tbl = deepcopy(doc_table._tbl)
    # 定位最后一行
    page = document.paragraphs[len(document.paragraphs) - 1]
    page._p.addnext(new_tbl)
2、表格赋值
	table = tables[i]
    table.cell(0, 2).text = str(sheet.cell(i, 1).value)

三、最终代码

前面模块都有了,进行一个组合即可。

from openpyxl import load_workbook
from copy import deepcopy
from docx import *

docFile = r'C:\Users\Administrator\Desktop\test.docx'
document = Document(docFile)

elxFile = r'C:\Users\Administrator\Desktop\test.xlsx'
excel = load_workbook(elxFile)
# 选择Sheet
sheet = excel['Sheet1']
max_row = sheet.max_row
max_cow = sheet.max_column


def _combine_docx(document):
    """
    Takes a list of docx.Documents and performs a deepcopy on the
    first table in each document and adds the copies successively to
    the first document in the list.
    """
    # 新增页
    document.add_page_break()

    # 原表格模版
    doc_table = document.tables[0]
    new_tbl = deepcopy(doc_table._tbl)
    # 定位最后一行
    page = document.paragraphs[len(document.paragraphs) - 1]
    page._p.addnext(new_tbl)


# 插入docx内容
def _insert_docx(i, tables):
    table = tables[i - 2]
    # cell两个参数:行数,列数
    table.cell(0, 2).text = str(sheet.cell(i, 1).value)


# 创建表格
for row in range(2, max_row):
    _combine_docx(document)

# 表格创建之后先进行保存
document.save(docFile)

document = Document(docFile)
tables = document.tables
# 表格中填入内容
# 从第二行开始执行,最大次数为最大行数 + 1
for row in range(2, max_row + 1):
    _insert_docx(row, tables)

# 保存文件
document.save(docFile)

至于中间为什么还需要执行document = Document(docFile),只能说懂得都懂,不懂的我也不能乱说?

猜你喜欢

转载自blog.csdn.net/qq_16253859/article/details/107861827