使用Python實(shí)現(xiàn)Word文檔處理自動(dòng)化的操作方法
使用python-docx操作Word文檔
Python-docx是一個(gè)強(qiáng)大的庫(kù),可以用來(lái)創(chuàng)建、讀取和修改Microsoft Word (.docx)文檔。它提供了豐富的API來(lái)操作文檔的各個(gè)方面,包括段落、表格、圖片等。
安裝python-docx
pip install python-docx
創(chuàng)建新的Word文檔
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
def create_simple_document():
"""創(chuàng)建一個(gè)簡(jiǎn)單的Word文檔"""
# 創(chuàng)建文檔對(duì)象
doc = Document()
# 添加標(biāo)題
doc.add_heading('Python自動(dòng)化辦公指南', 0)
# 添加段落
p = doc.add_paragraph('使用 ')
p.add_run('python-docx').bold = True
p.add_run(' 可以輕松創(chuàng)建和修改Word文檔,這對(duì)于')
p.add_run('自動(dòng)化辦公').italic = True
p.add_run('非常有用。')
# 添加一級(jí)標(biāo)題
doc.add_heading('1. 文檔基礎(chǔ)', level=1)
# 添加帶樣式的段落
paragraph = doc.add_paragraph('這是一個(gè)普通段落,展示了如何添加文本內(nèi)容。')
paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# 添加項(xiàng)目符號(hào)列表
doc.add_paragraph('項(xiàng)目符號(hào)列表示例:', style='List Bullet')
doc.add_paragraph('第一項(xiàng)', style='List Bullet')
doc.add_paragraph('第二項(xiàng)', style='List Bullet')
doc.add_paragraph('第三項(xiàng)', style='List Bullet')
# 添加編號(hào)列表
doc.add_paragraph('編號(hào)列表示例:', style='List Number')
doc.add_paragraph('第一步', style='List Number')
doc.add_paragraph('第二步', style='List Number')
doc.add_paragraph('第三步', style='List Number')
# 添加圖片
doc.add_heading('2. 插入圖片', level=1)
doc.add_paragraph('下面是一個(gè)圖片示例:')
try:
doc.add_picture('example.png', width=Inches(4.0))
except:
doc.add_paragraph('(圖片文件不存在,請(qǐng)?zhí)鎿Q為實(shí)際圖片路徑)')
# 添加表格
doc.add_heading('3. 創(chuàng)建表格', level=1)
doc.add_paragraph('下面是一個(gè)3x3表格示例:')
table = doc.add_table(rows=3, cols=3)
table.style = 'Table Grid'
# 填充表頭
header_cells = table.rows[0].cells
header_cells[0].text = '姓名'
header_cells[1].text = '年齡'
header_cells[2].text = '職位'
# 填充數(shù)據(jù)行
data = [
['張三', '28', '工程師'],
['李四', '32', '設(shè)計(jì)師']
]
for i, row_data in enumerate(data):
row = table.rows[i+1].cells
for j, val in enumerate(row_data):
row[j].text = val
# 添加分頁(yè)符
doc.add_page_break()
# 添加頁(yè)眉和頁(yè)腳
section = doc.sections[0]
header = section.header
header.paragraphs[0].text = "Python自動(dòng)化辦公 - 頁(yè)眉示例"
header.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.text = "第 "
footer_para.add_run("PAGENUM").bold = True
footer_para.add_run(" 頁(yè)")
footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 保存文檔
doc.save('簡(jiǎn)單文檔示例.docx')
print("文檔已創(chuàng)建: 簡(jiǎn)單文檔示例.docx")
# 執(zhí)行函數(shù)
create_simple_document()
修改現(xiàn)有Word文檔
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
def modify_existing_document(file_path):
"""修改現(xiàn)有Word文檔"""
try:
# 打開(kāi)現(xiàn)有文檔
doc = Document(file_path)
# 修改文檔標(biāo)題(假設(shè)第一個(gè)段落是標(biāo)題)
if doc.paragraphs:
title = doc.paragraphs[0]
title.text = "更新后的文檔標(biāo)題"
title.runs[0].bold = True
title.runs[0].font.size = Pt(18)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 在文檔末尾添加新內(nèi)容
doc.add_heading('新增章節(jié)', level=1)
doc.add_paragraph('這是修改文檔后添加的新內(nèi)容。')
# 修改表格內(nèi)容(如果存在)
if doc.tables:
table = doc.tables[0] # 獲取第一個(gè)表格
if len(table.rows) > 1 and len(table.rows[1].cells) > 0:
# 修改第二行第一列的內(nèi)容
table.rows[1].cells[0].text = "更新的內(nèi)容"
# 保存修改后的文檔(可以選擇另存為新文件)
modified_file = "修改后_" + file_path
doc.save(modified_file)
print(f"文檔已修改并保存為: {modified_file}")
return True
except Exception as e:
print(f"修改文檔時(shí)出錯(cuò): {e}")
return False
# 使用示例
# modify_existing_document("簡(jiǎn)單文檔示例.docx")
提取Word文檔內(nèi)容
from docx import Document
def extract_document_content(file_path):
"""提取Word文檔中的內(nèi)容"""
try:
# 打開(kāi)文檔
doc = Document(file_path)
# 提取所有段落文本
paragraphs_text = [para.text for para in doc.paragraphs if para.text]
print("\n文檔段落內(nèi)容:")
for i, text in enumerate(paragraphs_text, 1):
print(f"{i}. {text[:100]}{'...' if len(text) > 100 else ''}")
# 提取所有表格內(nèi)容
tables_data = []
for i, table in enumerate(doc.tables):
print(f"\n表格 {i+1}:")
table_data = []
for row in table.rows:
row_data = [cell.text for cell in row.cells]
table_data.append(row_data)
print(" | ".join(row_data))
tables_data.append(table_data)
# 返回提取的內(nèi)容
return {
"paragraphs": paragraphs_text,
"tables": tables_data
}
except Exception as e:
print(f"提取文檔內(nèi)容時(shí)出錯(cuò): {e}")
return None
# 使用示例
# content = extract_document_content("簡(jiǎn)單文檔示例.docx")
創(chuàng)建復(fù)雜格式文檔
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
def create_complex_document():
"""創(chuàng)建具有復(fù)雜格式的Word文檔"""
# 創(chuàng)建文檔對(duì)象
doc = Document()
# 設(shè)置文檔樣式
styles = doc.styles
# 創(chuàng)建自定義標(biāo)題樣式
title_style = styles.add_style('CustomTitle', WD_STYLE_TYPE.PARAGRAPH)
title_font = title_style.font
title_font.name = '微軟雅黑'
title_font.size = Pt(24)
title_font.bold = True
title_font.color.rgb = RGBColor(0, 112, 192) # 藍(lán)色
# 添加標(biāo)題
title = doc.add_paragraph("項(xiàng)目進(jìn)度報(bào)告", style='CustomTitle')
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加日期
from datetime import date
date_paragraph = doc.add_paragraph(f"日期: {date.today().strftime('%Y年%m月%d日')}")
date_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
# 添加分隔線
p = doc.add_paragraph()
p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.SINGLE
run = p.add_run("_" * 80)
run.font.color.rgb = RGBColor(192, 192, 192) # 淺灰色
# 添加項(xiàng)目概述
doc.add_heading("1. 項(xiàng)目概述", level=1)
doc.add_paragraph(
"本項(xiàng)目旨在開(kāi)發(fā)一套自動(dòng)化辦公系統(tǒng),提高企業(yè)內(nèi)部文檔處理效率。"
"系統(tǒng)將集成多種功能,包括文檔生成、數(shù)據(jù)分析和報(bào)表輸出等。"
)
# 添加項(xiàng)目進(jìn)度表
doc.add_heading("2. 項(xiàng)目進(jìn)度", level=1)
progress_table = doc.add_table(rows=1, cols=4)
progress_table.style = 'Table Grid'
# 設(shè)置表頭
header_cells = progress_table.rows[0].cells
headers = ["階段", "計(jì)劃完成時(shí)間", "實(shí)際完成時(shí)間", "完成度"]
for i, header in enumerate(headers):
header_cells[i].text = header
# 設(shè)置表頭背景色
shading_elm = OxmlElement('w:shd')
shading_elm.set(qn('w:fill'), "D9E1F2") # 淺藍(lán)色背景
header_cells[i]._tc.get_or_add_tcPr().append(shading_elm)
# 添加數(shù)據(jù)行
progress_data = [
["需求分析", "2023-01-15", "2023-01-20", "100%"],
["系統(tǒng)設(shè)計(jì)", "2023-02-28", "2023-03-05", "100%"],
["開(kāi)發(fā)階段", "2023-05-30", "進(jìn)行中", "65%"],
["測(cè)試階段", "2023-06-30", "未開(kāi)始", "0%"],
["部署上線", "2023-07-15", "未開(kāi)始", "0%"]
]
for data_row in progress_data:
row_cells = progress_table.add_row().cells
for i, val in enumerate(data_row):
row_cells[i].text = val
# 調(diào)整表格寬度
for cell in progress_table.columns[0].cells:
cell.width = Inches(1.5)
for cell in progress_table.columns[3].cells:
cell.width = Inches(1.0)
# 添加風(fēng)險(xiǎn)評(píng)估
doc.add_heading("3. 風(fēng)險(xiǎn)評(píng)估", level=1)
# 添加帶顏色的風(fēng)險(xiǎn)等級(jí)
risk_para = doc.add_paragraph("當(dāng)前項(xiàng)目風(fēng)險(xiǎn)等級(jí): ")
risk_run = risk_para.add_run("中等")
risk_run.font.color.rgb = RGBColor(255, 192, 0) # 橙色
risk_run.font.bold = True
# 添加風(fēng)險(xiǎn)列表
doc.add_paragraph("主要風(fēng)險(xiǎn)因素:", style='List Bullet')
risks = [
"技術(shù)實(shí)現(xiàn)難度超出預(yù)期",
"團(tuán)隊(duì)成員變動(dòng)",
"需求變更頻繁"
]
for risk in risks:
doc.add_paragraph(risk, style='List Bullet')
# 添加下一步計(jì)劃
doc.add_heading("4. 下一步計(jì)劃", level=1)
next_steps = [
"完成核心功能開(kāi)發(fā)",
"開(kāi)始內(nèi)部測(cè)試",
"準(zhǔn)備用戶培訓(xùn)材料"
]
for i, step in enumerate(next_steps, 1):
doc.add_paragraph(f"{i}. {step}", style='List Number')
# 添加頁(yè)腳
section = doc.sections[0]
footer = section.footer
footer_para = footer.paragraphs[0]
footer_para.text = "機(jī)密文件 - 僅供內(nèi)部使用"
footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 保存文檔
doc.save('項(xiàng)目進(jìn)度報(bào)告.docx')
print("復(fù)雜格式文檔已創(chuàng)建: 項(xiàng)目進(jìn)度報(bào)告.docx")
# 執(zhí)行函數(shù)
# create_complex_document()
使用docx-mailmerge填充Word模板
Word模板是包含固定格式設(shè)置和版式設(shè)置的Word文件,通過(guò)模板文件,可以快速生成美觀的Word文檔,而不再需要重新設(shè)置各種樣式的參數(shù)。docx-mailmerge庫(kù)可以方便地將數(shù)據(jù)填充到Word模板中的占位符位置。
安裝docx-mailmerge
pip install docx-mailmerge
創(chuàng)建Word模板
首先,需要在Word中創(chuàng)建一個(gè)包含合并域的模板文件。合并域是特殊的占位符,格式為«字段名»。
在Word中創(chuàng)建合并域的步驟:
- 打開(kāi)Word,創(chuàng)建新文檔
- 點(diǎn)擊「插入」選項(xiàng)卡
- 點(diǎn)擊「快速部件」→「域」
- 在「域」對(duì)話框中,選擇「MergeField」
- 在「域名稱」中輸入你的字段名(如「name」、「date」等)
- 點(diǎn)擊「確定」
使用Python填充Word模板
from mailmerge import MailMerge
from datetime import date
def fill_word_template(template_path, output_path, data):
"""填充Word模板文件"""
try:
# 打開(kāi)模板文件
document = MailMerge(template_path)
# 顯示模板中的所有合并域
print("模板中的合并域:", document.get_merge_fields())
# 填充數(shù)據(jù)
document.merge(**data)
# 保存生成的文檔
document.write(output_path)
print(f"已生成文檔: {output_path}")
return True
except Exception as e:
print(f"填充模板時(shí)出錯(cuò): {e}")
return False
# 使用示例 - 填充簡(jiǎn)單的信函模板
def generate_letter():
# 假設(shè)我們有一個(gè)名為"letter_template.docx"的模板,包含以下合并域:
# ?recipient_name?, ?recipient_address?, ?date?, ?subject?, ?content?, ?sender_name?, ?sender_title?
# 準(zhǔn)備數(shù)據(jù)
letter_data = {
'recipient_name': '張三',
'recipient_address': '北京市海淀區(qū)中關(guān)村南大街5號(hào)',
'date': date.today().strftime('%Y年%m月%d日'),
'subject': '項(xiàng)目合作邀請(qǐng)',
'content': '我們誠(chéng)摯地邀請(qǐng)貴公司參與我們即將啟動(dòng)的人工智能項(xiàng)目合作。該項(xiàng)目旨在開(kāi)發(fā)一套智能辦公系統(tǒng),提高企業(yè)運(yùn)營(yíng)效率。\n\n我們了解到貴公司在相關(guān)領(lǐng)域有豐富的經(jīng)驗(yàn),相信通過(guò)合作,我們可以共同創(chuàng)造更大的價(jià)值。\n\n期待您的回復(fù)。',
'sender_name': '李四',
'sender_title': '項(xiàng)目經(jīng)理'
}
# 填充模板
fill_word_template('letter_template.docx', '項(xiàng)目合作邀請(qǐng)函.docx', letter_data)
# 使用示例 - 批量生成證書(shū)
def generate_certificates():
# 假設(shè)我們有一個(gè)名為"certificate_template.docx"的模板,包含以下合并域:
# ?name?, ?course?, ?date?, ?instructor?, ?certificate_id?
# 準(zhǔn)備多組數(shù)據(jù)
students = [
{
'name': '王小明',
'course': 'Python高級(jí)編程',
'date': '2023年6月15日',
'instructor': '張教授',
'certificate_id': 'CERT-2023-001'
},
{
'name': '李小紅',
'course': 'Python高級(jí)編程',
'date': '2023年6月15日',
'instructor': '張教授',
'certificate_id': 'CERT-2023-002'
},
{
'name': '趙小青',
'course': 'Python高級(jí)編程',
'date': '2023年6月15日',
'instructor': '張教授',
'certificate_id': 'CERT-2023-003'
}
]
# 批量生成證書(shū)
for i, student in enumerate(students):
output_file = f"證書(shū)_{student['name']}.docx"
fill_word_template('certificate_template.docx', output_file, student)
# 執(zhí)行函數(shù)
# generate_letter()
# generate_certificates()
處理表格和重復(fù)項(xiàng)
from mailmerge import MailMerge
def fill_template_with_tables():
"""填充包含表格和重復(fù)項(xiàng)的Word模板"""
# 假設(shè)我們有一個(gè)名為"report_template.docx"的模板
# 該模板包含普通合并域和表格中的合并域
# 打開(kāi)模板
document = MailMerge('report_template.docx')
# 顯示所有合并域
print("模板中的合并域:", document.get_merge_fields())
# 填充普通合并域
document.merge(
report_title='月度銷售報(bào)告',
report_date='2023年7月1日',
prepared_by='市場(chǎng)部',
total_sales='¥1,234,567.00'
)
# 準(zhǔn)備表格數(shù)據(jù)(假設(shè)模板中有一個(gè)表格,包含產(chǎn)品銷售數(shù)據(jù))
# 表格中的合并域格式為: ?product:X?, ?quantity:X?, ?unit_price:X?, ?subtotal:X?
# 其中X是行索引
sales_data = [
{
'product': '筆記本電腦',
'quantity': '10',
'unit_price': '¥5,999.00',
'subtotal': '¥59,990.00'
},
{
'product': '辦公椅',
'quantity': '20',
'unit_price': '¥899.00',
'subtotal': '¥17,980.00'
},
{
'product': '打印機(jī)',
'quantity': '5',
'unit_price': '¥1,299.00',
'subtotal': '¥6,495.00'
}
]
# 合并表格數(shù)據(jù)
document.merge_rows('product', sales_data)
# 保存生成的文檔
document.write('月度銷售報(bào)告.docx')
print("已生成報(bào)告: 月度銷售報(bào)告.docx")
# 執(zhí)行函數(shù)
# fill_template_with_tables()
實(shí)際應(yīng)用場(chǎng)景
場(chǎng)景一:自動(dòng)生成合同
from mailmerge import MailMerge
from datetime import date
import os
def generate_contract(contract_data, template_path, output_dir):
"""根據(jù)模板自動(dòng)生成合同"""
# 確保輸出目錄存在
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 合同文件名
contract_filename = f"合同_{contract_data['contract_id']}_{contract_data['client_name']}.docx"
output_path = os.path.join(output_dir, contract_filename)
try:
# 打開(kāi)模板
document = MailMerge(template_path)
# 填充合同數(shù)據(jù)
document.merge(**contract_data)
# 保存生成的合同
document.write(output_path)
print(f"已生成合同: {contract_filename}")
return output_path
except Exception as e:
print(f"生成合同時(shí)出錯(cuò): {e}")
return None
# 使用示例
def batch_generate_contracts():
# 合同模板路徑
template_path = "contract_template.docx"
# 輸出目錄
output_dir = "generated_contracts"
# 準(zhǔn)備多份合同數(shù)據(jù)
contracts = [
{
'contract_id': 'CT-2023-001',
'client_name': '北京科技有限公司',
'client_address': '北京市朝陽(yáng)區(qū)建國(guó)路88號(hào)',
'client_representative': '王總',
'contract_date': date.today().strftime('%Y年%m月%d日'),
'start_date': '2023年8月1日',
'end_date': '2024年7月31日',
'contract_amount': '¥500,000.00',
'payment_terms': '分三期支付,首期款¥200,000.00,第二期款¥150,000.00,尾款¥150,000.00',
'service_scope': '軟件開(kāi)發(fā)、系統(tǒng)維護(hù)、技術(shù)支持',
'our_company': '智能科技有限公司',
'our_representative': '張總',
'our_address': '上海市浦東新區(qū)張江高科技園區(qū)'
},
{
'contract_id': 'CT-2023-002',
'client_name': '廣州貿(mào)易有限公司',
'client_address': '廣州市天河區(qū)珠江新城',
'client_representative': '李總',
'contract_date': date.today().strftime('%Y年%m月%d日'),
'start_date': '2023年9月1日',
'end_date': '2024年8月31日',
'contract_amount': '¥350,000.00',
'payment_terms': '分兩期支付,首期款¥200,000.00,尾款¥150,000.00',
'service_scope': '系統(tǒng)集成、數(shù)據(jù)遷移、用戶培訓(xùn)',
'our_company': '智能科技有限公司',
'our_representative': '張總',
'our_address': '上海市浦東新區(qū)張江高科技園區(qū)'
}
]
# 批量生成合同
generated_files = []
for contract_data in contracts:
contract_file = generate_contract(contract_data, template_path, output_dir)
if contract_file:
generated_files.append(contract_file)
print(f"共生成 {len(generated_files)} 份合同文件")
return generated_files
# 執(zhí)行批量生成合同
# batch_generate_contracts()
場(chǎng)景二:自動(dòng)生成個(gè)性化簡(jiǎn)歷
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
def create_resume(person_data, output_path):
"""創(chuàng)建個(gè)性化簡(jiǎn)歷"""
# 創(chuàng)建文檔
doc = Document()
# 設(shè)置頁(yè)邊距
sections = doc.sections
for section in sections:
section.top_margin = Inches(0.8)
section.bottom_margin = Inches(0.8)
section.left_margin = Inches(0.8)
section.right_margin = Inches(0.8)
# 添加姓名作為標(biāo)題
name = doc.add_heading(person_data['name'], 0)
name.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加聯(lián)系方式
contact_info = f"電話: {person_data['phone']} | 郵箱: {person_data['email']} | 地址: {person_data['address']}"
contact = doc.add_paragraph(contact_info)
contact.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加分隔線
doc.add_paragraph('_' * 80)
# 添加個(gè)人簡(jiǎn)介
doc.add_heading('個(gè)人簡(jiǎn)介', level=1)
doc.add_paragraph(person_data['summary'])
# 添加教育背景
doc.add_heading('教育背景', level=1)
for edu in person_data['education']:
p = doc.add_paragraph()
p.add_run(f"{edu['school']} - {edu['degree']}").bold = True
p.add_run(f"\n{edu['date']}")
p.add_run(f"\n{edu['description']}")
# 添加工作經(jīng)驗(yàn)
doc.add_heading('工作經(jīng)驗(yàn)', level=1)
for job in person_data['experience']:
p = doc.add_paragraph()
p.add_run(f"{job['company']} - {job['position']}").bold = True
p.add_run(f"\n{job['date']}")
# 添加工作職責(zé)
doc.add_paragraph('職責(zé):', style='List Bullet')
for responsibility in job['responsibilities']:
doc.add_paragraph(responsibility, style='List Bullet')
# 添加技能
doc.add_heading('技能', level=1)
for category, skills in person_data['skills'].items():
p = doc.add_paragraph()
p.add_run(f"{category}: ").bold = True
p.add_run(', '.join(skills))
# 保存文檔
doc.save(output_path)
print(f"簡(jiǎn)歷已生成: {output_path}")
return output_path
# 使用示例
def generate_sample_resume():
# 準(zhǔn)備簡(jiǎn)歷數(shù)據(jù)
resume_data = {
'name': '張三',
'phone': '138-1234-5678',
'email': 'zhangsan@example.com',
'address': '北京市海淀區(qū)',
'summary': '資深軟件工程師,擁有8年P(guān)ython開(kāi)發(fā)經(jīng)驗(yàn),專注于數(shù)據(jù)分析和自動(dòng)化系統(tǒng)開(kāi)發(fā)。具有良好的團(tuán)隊(duì)協(xié)作能力和項(xiàng)目管理經(jīng)驗(yàn)。',
'education': [
{
'school': '北京大學(xué)',
'degree': '計(jì)算機(jī)科學(xué)學(xué)士',
'date': '2010 - 2014',
'description': '主修計(jì)算機(jī)科學(xué)與技術(shù),輔修數(shù)學(xué)。GPA 3.8/4.0。'
},
{
'school': '清華大學(xué)',
'degree': '軟件工程碩士',
'date': '2014 - 2016',
'description': '研究方向:機(jī)器學(xué)習(xí)與數(shù)據(jù)挖掘。'
}
],
'experience': [
{
'company': 'ABC科技有限公司',
'position': '高級(jí)軟件工程師',
'date': '2019 - 至今',
'responsibilities': [
'負(fù)責(zé)公司核心數(shù)據(jù)處理平臺(tái)的設(shè)計(jì)和開(kāi)發(fā)',
'優(yōu)化數(shù)據(jù)處理流程,提高系統(tǒng)性能30%',
'帶領(lǐng)5人團(tuán)隊(duì)完成多個(gè)重要項(xiàng)目',
'引入自動(dòng)化測(cè)試,提高代碼質(zhì)量'
]
},
{
'company': 'XYZ信息技術(shù)公司',
'position': '軟件工程師',
'date': '2016 - 2019',
'responsibilities': [
'參與開(kāi)發(fā)企業(yè)級(jí)數(shù)據(jù)分析系統(tǒng)',
'設(shè)計(jì)并實(shí)現(xiàn)數(shù)據(jù)可視化模塊',
'編寫(xiě)技術(shù)文檔和用戶手冊(cè)',
'為新員工提供技術(shù)培訓(xùn)'
]
}
],
'skills': {
'編程語(yǔ)言': ['Python', 'Java', 'JavaScript', 'SQL'],
'框架與工具': ['Django', 'Flask', 'React', 'Docker', 'Git'],
'數(shù)據(jù)庫(kù)': ['MySQL', 'MongoDB', 'Redis'],
'其他': ['數(shù)據(jù)分析', '機(jī)器學(xué)習(xí)', '項(xiàng)目管理', '團(tuán)隊(duì)協(xié)作']
}
}
# 生成簡(jiǎn)歷
return create_resume(resume_data, '張三_個(gè)人簡(jiǎn)歷.docx')
# 執(zhí)行生成簡(jiǎn)歷
# generate_sample_resume()
場(chǎng)景三:自動(dòng)生成周報(bào)/月報(bào)
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from datetime import datetime, timedelta
import calendar
def generate_weekly_report(week_data, output_path):
"""生成周報(bào)"""
# 創(chuàng)建文檔
doc = Document()
# 添加標(biāo)題
title = doc.add_heading(f"{week_data['department']}周報(bào)", 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加報(bào)告期間
period = doc.add_paragraph(f"報(bào)告期間: {week_data['start_date']} 至 {week_data['end_date']}")
period.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加報(bào)告人和日期
reporter = doc.add_paragraph(f"報(bào)告人: {week_data['reporter']}\t\t報(bào)告日期: {week_data['report_date']}")
reporter.alignment = WD_ALIGN_PARAGRAPH.RIGHT
# 添加分隔線
doc.add_paragraph('_' * 80)
# 本周工作總結(jié)
doc.add_heading('一、本周工作總結(jié)', level=1)
for i, task in enumerate(week_data['completed_tasks'], 1):
p = doc.add_paragraph(f"{i}. ", style='List Number')
p.add_run(task['name']).bold = True
p.add_run(f"\n 完成情況: {task['status']}")
p.add_run(f"\n 工作內(nèi)容: {task['description']}")
# 下周工作計(jì)劃
doc.add_heading('二、下周工作計(jì)劃', level=1)
for i, task in enumerate(week_data['planned_tasks'], 1):
p = doc.add_paragraph(f"{i}. ", style='List Number')
p.add_run(task['name']).bold = True
p.add_run(f"\n 計(jì)劃時(shí)間: {task['planned_time']}")
p.add_run(f"\n 工作內(nèi)容: {task['description']}")
# 問(wèn)題與建議
if week_data['issues']:
doc.add_heading('三、問(wèn)題與建議', level=1)
for i, issue in enumerate(week_data['issues'], 1):
p = doc.add_paragraph(f"{i}. ", style='List Number')
p.add_run(issue['title']).bold = True
p.add_run(f"\n 問(wèn)題描述: {issue['description']}")
if issue.get('solution'):
p.add_run(f"\n 解決方案: {issue['solution']}")
# 保存文檔
doc.save(output_path)
print(f"周報(bào)已生成: {output_path}")
return output_path
# 使用示例
def create_sample_weekly_report():
# 計(jì)算上周的日期范圍
today = datetime.now()
start_of_last_week = today - timedelta(days=today.weekday() + 7)
end_of_last_week = start_of_last_week + timedelta(days=6)
# 準(zhǔn)備周報(bào)數(shù)據(jù)
week_data = {
'department': '技術(shù)部',
'start_date': start_of_last_week.strftime('%Y年%m月%d日'),
'end_date': end_of_last_week.strftime('%Y年%m月%d日'),
'reporter': '張三',
'report_date': today.strftime('%Y年%m月%d日'),
'completed_tasks': [
{
'name': '用戶管理模塊開(kāi)發(fā)',
'status': '已完成',
'description': '完成了用戶注冊(cè)、登錄、權(quán)限管理等功能的開(kāi)發(fā)和單元測(cè)試。'
},
{
'name': '數(shù)據(jù)導(dǎo)入功能優(yōu)化',
'status': '已完成',
'description': '優(yōu)化了大數(shù)據(jù)量導(dǎo)入的性能,提高了處理速度約40%。'
},
{
'name': 'Bug修復(fù)',
'status': '進(jìn)行中 (80%)',
'description': '修復(fù)了上周反饋的10個(gè)Bug中的8個(gè),剩余2個(gè)正在處理中。'
}
],
'planned_tasks': [
{
'name': '完成剩余Bug修復(fù)',
'planned_time': '下周一至周二',
'description': '解決剩余的2個(gè)Bug,并進(jìn)行回歸測(cè)試。'
},
{
'name': '開(kāi)始報(bào)表模塊開(kāi)發(fā)',
'planned_time': '下周三至周五',
'description': '設(shè)計(jì)并實(shí)現(xiàn)數(shù)據(jù)報(bào)表功能,包括數(shù)據(jù)統(tǒng)計(jì)和可視化展示。'
},
{
'name': '代碼審查與重構(gòu)',
'planned_time': '下周五',
'description': '對(duì)現(xiàn)有代碼進(jìn)行審查,優(yōu)化代碼結(jié)構(gòu)和性能。'
}
],
'issues': [
{
'title': '性能問(wèn)題',
'description': '在高并發(fā)情況下,系統(tǒng)響應(yīng)速度明顯下降。',
'solution': '計(jì)劃通過(guò)引入緩存機(jī)制和優(yōu)化數(shù)據(jù)庫(kù)查詢來(lái)解決。'
},
{
'title': '團(tuán)隊(duì)協(xié)作效率',
'description': '當(dāng)前的代碼版本管理流程較為復(fù)雜,影響開(kāi)發(fā)效率。',
'solution': '建議簡(jiǎn)化Git工作流,并加強(qiáng)團(tuán)隊(duì)培訓(xùn)。'
}
]
}
# 生成周報(bào)
return generate_weekly_report(week_data, f"技術(shù)部周報(bào)_{week_data['start_date']}_{week_data['end_date']}.docx")
# 執(zhí)行生成周報(bào)
# create_sample_weekly_report()
通過(guò)以上代碼示例和應(yīng)用場(chǎng)景,你可以輕松掌握Python Word文檔自動(dòng)化的各種技巧,大幅提高工作效率。無(wú)論是創(chuàng)建簡(jiǎn)單的文檔,還是生成復(fù)雜的報(bào)告、合同或簡(jiǎn)歷,Python都能幫你輕松應(yīng)對(duì)。
以上就是使用Python實(shí)現(xiàn)Word文檔處理自動(dòng)化的操作方法的詳細(xì)內(nèi)容,更多關(guān)于Python Word文檔處理自動(dòng)化的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python3 讀取Excel表格中的數(shù)據(jù)
這篇文章主要介紹了python3 讀取Excel表格中的數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2018-10-10
Python基于pygame實(shí)現(xiàn)圖片代替鼠標(biāo)移動(dòng)效果
這篇文章主要介紹了Python基于pygame實(shí)現(xiàn)圖片代替鼠標(biāo)移動(dòng)效果,可實(shí)現(xiàn)將鼠標(biāo)箭頭轉(zhuǎn)換成圖形的功能,涉及pygame圖形操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例
本篇文章主要介紹了Python實(shí)現(xiàn)Smtplib發(fā)送帶有各種附件的郵件實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
python 根據(jù)時(shí)間來(lái)生成唯一的字符串方法
今天小編就為大家分享一篇python 根據(jù)時(shí)間來(lái)生成唯一的字符串方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
Python基于FastAPI和WebSocket實(shí)現(xiàn)實(shí)時(shí)聊天應(yīng)用
這篇文章主要為大家詳細(xì)介紹了Python如何基于FastAPI和WebSocket實(shí)現(xiàn)實(shí)時(shí)聊天應(yīng)用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
Python+pyftpdlib實(shí)現(xiàn)局域網(wǎng)文件互傳
這篇文章主要介紹了Python+pyftpdlib實(shí)現(xiàn)局域網(wǎng)文件互傳,需要的朋友可以參考下2020-08-08

