需求
1.讀取一個已有的word文檔。docx格式。
2.在該word文檔中,通過一個給定的文字。找到該位置。在該位置的下方添加一個表格。例如在圖中“BUG情況表”的下方插入一個表格
3.表格内容如下。要求添加完該表格後,如果表格内容發生變更。還能再次通過該程式,修改表格裡的資料。
設計
通過python-docx讀取word文檔。通過document.paragraphs定位指定文字的位置。
通過xlwings讀取excel的内容,存成list[list[]]。
通過docx的add_table增加一個表格,并且更改表頭顔色,合并表格等操作
通過識别表頭的第一行,判斷是否是已經存在這個表格,來決定是否要删除原表格
代碼
# -*- coding: UTF-8 -*-
import sys
from copy import deepcopy
import xlwings
from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
def copy_table_after(table, paragraph):
tbl, p = table._tbl, paragraph._p
new_tbl = deepcopy(tbl)
p.addnext(new_tbl)
def move_table_after(table, paragraph):
tbl, p = table._tbl, paragraph._p
p.addnext(tbl)
def get_excel_date(filename):
'''
獲得excel裡的所有内容,傳回list
:param filename: excel路徑
:return: list[list[]]
'''
app = xlwings.App(visible=False, add_book=True)
app.display_alerts = False
app.screen_updating = False
wb = app.books.open(filename)
sht = wb.sheets[0]
rng = sht.range('A1')
# 把excel裡的資料讀取成 年-月-日 時:分:秒的格式
my_date_handler = lambda year, month, day, hour, minute, second, **kwargs: "%04i-%02i-%02i %02i:%02i:%02i" % (
year, month, day, hour, minute, second)
# 取出所有内容,這裡用ig這個變量,是為了慶祝I.G獲得LOL S8賽季總冠軍
ig = rng.current_region.options(index=False, numbers=int, empty='N/A', dates=my_date_handler)
result = ig.value
wb.close()
app.quit()
return result
def delete_table_with_title(document,expect_text):
allTables = document.tables
for activeTable in allTables:
if activeTable.cell(0, 0).paragraphs[0].text == expect_text:
print('删除成功')
activeTable._element.getparent().remove(activeTable._element)
def insert_table_after_text(file_name,excel_name,expect_text):
document = Document(file_name)
# 因為docx讀出來的都是unicode類型的,是以我們要用unicode類型的進行查找
expect_text=expect_text.decode('utf-8')
delete_table_with_title(document,expect_text)
target = None
for paragraph in document.paragraphs:
paragraph_text = paragraph.text
if paragraph_text.endswith(expect_text):
target = paragraph
break
if target is not None:
records = get_excel_date(excel_name)
# 獲得excel資料的欄數,初始化一個空的table
col = len(records[0])
table = document.add_table(rows=1, cols=col)
table.style = 'Table Grid'
# 給table加一個表頭,并且合并第一欄
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="D9E2F3"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
table.rows[0].cells[0].text=expect_text
table_row=table.rows[0]
first=table_row.cells[0]
end=table_row.cells[-1]
first.merge(end)
# 合并結束,開始把excel裡的内容添加到table裡
for tr_list in records:
row_cells = table.add_row().cells
index = 0
for td_list in tr_list:
row_cells[index].text = td_list
index = index + 1
# 把添加的table移動到指定的位置
move_table_after(table, target)
# 儲存
document.save(file_name)
if __name__ == '__main__':
insert_table_after_text('demo2.docx', 'demo.xlsx',"BUG情況表")