Python實現(xiàn)Word文檔自動化處理操作
在日常辦公中,Word文檔是最常用的文本處理工具之一。通過Python自動化Word文檔操作,可以大幅提高工作效率,減少重復(fù)勞動,特別適合批量生成報告、合同、簡歷等標(biāo)準(zhǔn)化文檔。本文將介紹幾種常用的Python操作Word文檔的方法,并提供實用的代碼示例和應(yīng)用場景。
使用python-docx操作Word文檔
Python-docx是一個強(qiáng)大的庫,可以用來創(chuàng)建、讀取和修改Microsoft Word (.docx)文檔。它提供了豐富的API來操作文檔的各個方面,包括段落、表格、圖片等。
安裝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)建一個簡單的Word文檔"""
# 創(chuàng)建文檔對象
doc = Document()
# 添加標(biāo)題
doc.add_heading('Python自動化辦公指南', 0)
# 添加段落
p = doc.add_paragraph('使用 ')
p.add_run('python-docx').bold = True
p.add_run(' 可以輕松創(chuàng)建和修改Word文檔,這對于')
p.add_run('自動化辦公').italic = True
p.add_run('非常有用。')
# 添加一級標(biāo)題
doc.add_heading('1. 文檔基礎(chǔ)', level=1)
# 添加帶樣式的段落
paragraph = doc.add_paragraph('這是一個普通段落,展示了如何添加文本內(nèi)容。')
paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# 添加項目符號列表
doc.add_paragraph('項目符號列表示例:', style='List Bullet')
doc.add_paragraph('第一項', style='List Bullet')
doc.add_paragraph('第二項', style='List Bullet')
doc.add_paragraph('第三項', style='List Bullet')
# 添加編號列表
doc.add_paragraph('編號列表示例:', 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('下面是一個圖片示例:')
try:
doc.add_picture('example.png', width=Inches(4.0))
except:
doc.add_paragraph('(圖片文件不存在,請?zhí)鎿Q為實際圖片路徑)')
# 添加表格
doc.add_heading('3. 創(chuàng)建表格', level=1)
doc.add_paragraph('下面是一個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è)計師']
]
for i, row_data in enumerate(data):
row = table.rows[i+1].cells
for j, val in enumerate(row_data):
row[j].text = val
# 添加分頁符
doc.add_page_break()
# 添加頁眉和頁腳
section = doc.sections[0]
header = section.header
header.paragraphs[0].text = "Python自動化辦公 - 頁眉示例"
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(" 頁")
footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 保存文檔
doc.save('簡單文檔示例.docx')
print("文檔已創(chuàng)建: 簡單文檔示例.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:
# 打開現(xiàn)有文檔
doc = Document(file_path)
# 修改文檔標(biāo)題(假設(shè)第一個段落是標(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] # 獲取第一個表格
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"修改文檔時出錯: {e}")
return False
# 使用示例
# modify_existing_document("簡單文檔示例.docx")
提取Word文檔內(nèi)容
from docx import Document
def extract_document_content(file_path):
"""提取Word文檔中的內(nèi)容"""
try:
# 打開文檔
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)容時出錯: {e}")
return None
# 使用示例
# content = extract_document_content("簡單文檔示例.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)建文檔對象
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("項目進(jìn)度報告", 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) # 淺灰色
# 添加項目概述
doc.add_heading("1. 項目概述", level=1)
doc.add_paragraph(
"本項目旨在開發(fā)一套自動化辦公系統(tǒng),提高企業(yè)內(nèi)部文檔處理效率。"
"系統(tǒng)將集成多種功能,包括文檔生成、數(shù)據(jù)分析和報表輸出等。"
)
# 添加項目進(jìn)度表
doc.add_heading("2. 項目進(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 = ["階段", "計劃完成時間", "實際完成時間", "完成度"]
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è)計", "2023-02-28", "2023-03-05", "100%"],
["開發(fā)階段", "2023-05-30", "進(jìn)行中", "65%"],
["測試階段", "2023-06-30", "未開始", "0%"],
["部署上線", "2023-07-15", "未開始", "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)險評估
doc.add_heading("3. 風(fēng)險評估", level=1)
# 添加帶顏色的風(fēng)險等級
risk_para = doc.add_paragraph("當(dāng)前項目風(fēng)險等級: ")
risk_run = risk_para.add_run("中等")
risk_run.font.color.rgb = RGBColor(255, 192, 0) # 橙色
risk_run.font.bold = True
# 添加風(fēng)險列表
doc.add_paragraph("主要風(fēng)險因素:", style='List Bullet')
risks = [
"技術(shù)實現(xiàn)難度超出預(yù)期",
"團(tuán)隊成員變動",
"需求變更頻繁"
]
for risk in risks:
doc.add_paragraph(risk, style='List Bullet')
# 添加下一步計劃
doc.add_heading("4. 下一步計劃", level=1)
next_steps = [
"完成核心功能開發(fā)",
"開始內(nèi)部測試",
"準(zhǔn)備用戶培訓(xùn)材料"
]
for i, step in enumerate(next_steps, 1):
doc.add_paragraph(f"{i}. {step}", style='List Number')
# 添加頁腳
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('項目進(jìn)度報告.docx')
print("復(fù)雜格式文檔已創(chuàng)建: 項目進(jìn)度報告.docx")
# 執(zhí)行函數(shù)
# create_complex_document()
使用docx-mailmerge填充Word模板
Word模板是包含固定格式設(shè)置和版式設(shè)置的Word文件,通過模板文件,可以快速生成美觀的Word文檔,而不再需要重新設(shè)置各種樣式的參數(shù)。docx-mailmerge庫可以方便地將數(shù)據(jù)填充到Word模板中的占位符位置。
安裝docx-mailmerge
pip install docx-mailmerge
創(chuàng)建Word模板
首先,需要在Word中創(chuàng)建一個包含合并域的模板文件。合并域是特殊的占位符,格式為«字段名»。
在Word中創(chuàng)建合并域的步驟:
- 打開Word,創(chuàng)建新文檔
- 點擊「插入」選項卡
- 點擊「快速部件」→「域」
- 在「域」對話框中,選擇「MergeField」
- 在「域名稱」中輸入你的字段名(如「name」、「date」等)
- 點擊「確定」
使用Python填充Word模板
from mailmerge import MailMerge
from datetime import date
def fill_word_template(template_path, output_path, data):
"""填充Word模板文件"""
try:
# 打開模板文件
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"填充模板時出錯: {e}")
return False
# 使用示例 - 填充簡單的信函模板
def generate_letter():
# 假設(shè)我們有一個名為"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號',
'date': date.today().strftime('%Y年%m月%d日'),
'subject': '項目合作邀請',
'content': '我們誠摯地邀請貴公司參與我們即將啟動的人工智能項目合作。該項目旨在開發(fā)一套智能辦公系統(tǒng),提高企業(yè)運(yùn)營效率。\n\n我們了解到貴公司在相關(guān)領(lǐng)域有豐富的經(jīng)驗,相信通過合作,我們可以共同創(chuàng)造更大的價值。\n\n期待您的回復(fù)。',
'sender_name': '李四',
'sender_title': '項目經(jīng)理'
}
# 填充模板
fill_word_template('letter_template.docx', '項目合作邀請函.docx', letter_data)
# 使用示例 - 批量生成證書
def generate_certificates():
# 假設(shè)我們有一個名為"certificate_template.docx"的模板,包含以下合并域:
# ?name?, ?course?, ?date?, ?instructor?, ?certificate_id?
# 準(zhǔn)備多組數(shù)據(jù)
students = [
{
'name': '王小明',
'course': 'Python高級編程',
'date': '2023年6月15日',
'instructor': '張教授',
'certificate_id': 'CERT-2023-001'
},
{
'name': '李小紅',
'course': 'Python高級編程',
'date': '2023年6月15日',
'instructor': '張教授',
'certificate_id': 'CERT-2023-002'
},
{
'name': '趙小青',
'course': 'Python高級編程',
'date': '2023年6月15日',
'instructor': '張教授',
'certificate_id': 'CERT-2023-003'
}
]
# 批量生成證書
for i, student in enumerate(students):
output_file = f"證書_{student['name']}.docx"
fill_word_template('certificate_template.docx', output_file, student)
# 執(zhí)行函數(shù)
# generate_letter()
# generate_certificates()
處理表格和重復(fù)項
from mailmerge import MailMerge
def fill_template_with_tables():
"""填充包含表格和重復(fù)項的Word模板"""
# 假設(shè)我們有一個名為"report_template.docx"的模板
# 該模板包含普通合并域和表格中的合并域
# 打開模板
document = MailMerge('report_template.docx')
# 顯示所有合并域
print("模板中的合并域:", document.get_merge_fields())
# 填充普通合并域
document.merge(
report_title='月度銷售報告',
report_date='2023年7月1日',
prepared_by='市場部',
total_sales='¥1,234,567.00'
)
# 準(zhǔn)備表格數(shù)據(jù)(假設(shè)模板中有一個表格,包含產(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('月度銷售報告.docx')
print("已生成報告: 月度銷售報告.docx")
# 執(zhí)行函數(shù)
# fill_template_with_tables()
實際應(yīng)用場景
場景一:自動生成合同
from mailmerge import MailMerge
from datetime import date
import os
def generate_contract(contract_data, template_path, output_dir):
"""根據(jù)模板自動生成合同"""
# 確保輸出目錄存在
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:
# 打開模板
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"生成合同時出錯: {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': '北京市朝陽區(qū)建國路88號',
'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': '軟件開發(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()
場景二:自動生成個性化簡歷
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)建個性化簡歷"""
# 創(chuàng)建文檔
doc = Document()
# 設(shè)置頁邊距
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)
# 添加個人簡介
doc.add_heading('個人簡介', 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)驗
doc.add_heading('工作經(jīng)驗', 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"簡歷已生成: {output_path}")
return output_path
# 使用示例
def generate_sample_resume():
# 準(zhǔn)備簡歷數(shù)據(jù)
resume_data = {
'name': '張三',
'phone': '138-1234-5678',
'email': 'zhangsan@example.com',
'address': '北京市海淀區(qū)',
'summary': '資深軟件工程師,擁有8年P(guān)ython開發(fā)經(jīng)驗,專注于數(shù)據(jù)分析和自動化系統(tǒng)開發(fā)。具有良好的團(tuán)隊協(xié)作能力和項目管理經(jīng)驗。',
'education': [
{
'school': '北京大學(xué)',
'degree': '計算機(jī)科學(xué)學(xué)士',
'date': '2010 - 2014',
'description': '主修計算機(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': '高級軟件工程師',
'date': '2019 - 至今',
'responsibilities': [
'負(fù)責(zé)公司核心數(shù)據(jù)處理平臺的設(shè)計和開發(fā)',
'優(yōu)化數(shù)據(jù)處理流程,提高系統(tǒng)性能30%',
'帶領(lǐng)5人團(tuán)隊完成多個重要項目',
'引入自動化測試,提高代碼質(zhì)量'
]
},
{
'company': 'XYZ信息技術(shù)公司',
'position': '軟件工程師',
'date': '2016 - 2019',
'responsibilities': [
'參與開發(fā)企業(yè)級數(shù)據(jù)分析系統(tǒng)',
'設(shè)計并實現(xiàn)數(shù)據(jù)可視化模塊',
'編寫技術(shù)文檔和用戶手冊',
'為新員工提供技術(shù)培訓(xùn)'
]
}
],
'skills': {
'編程語言': ['Python', 'Java', 'JavaScript', 'SQL'],
'框架與工具': ['Django', 'Flask', 'React', 'Docker', 'Git'],
'數(shù)據(jù)庫': ['MySQL', 'MongoDB', 'Redis'],
'其他': ['數(shù)據(jù)分析', '機(jī)器學(xué)習(xí)', '項目管理', '團(tuán)隊協(xié)作']
}
}
# 生成簡歷
return create_resume(resume_data, '張三_個人簡歷.docx')
# 執(zhí)行生成簡歷
# generate_sample_resume()
場景三:自動生成周報/月報
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):
"""生成周報"""
# 創(chuàng)建文檔
doc = Document()
# 添加標(biāo)題
title = doc.add_heading(f"{week_data['department']}周報", 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加報告期間
period = doc.add_paragraph(f"報告期間: {week_data['start_date']} 至 {week_data['end_date']}")
period.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加報告人和日期
reporter = doc.add_paragraph(f"報告人: {week_data['reporter']}\t\t報告日期: {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']}")
# 下周工作計劃
doc.add_heading('二、下周工作計劃', 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 計劃時間: {task['planned_time']}")
p.add_run(f"\n 工作內(nèi)容: {task['description']}")
# 問題與建議
if week_data['issues']:
doc.add_heading('三、問題與建議', 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 問題描述: {issue['description']}")
if issue.get('solution'):
p.add_run(f"\n 解決方案: {issue['solution']}")
# 保存文檔
doc.save(output_path)
print(f"周報已生成: {output_path}")
return output_path
# 使用示例
def create_sample_weekly_report():
# 計算上周的日期范圍
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)備周報數(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': '用戶管理模塊開發(fā)',
'status': '已完成',
'description': '完成了用戶注冊、登錄、權(quán)限管理等功能的開發(fā)和單元測試。'
},
{
'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個Bug中的8個,剩余2個正在處理中。'
}
],
'planned_tasks': [
{
'name': '完成剩余Bug修復(fù)',
'planned_time': '下周一至周二',
'description': '解決剩余的2個Bug,并進(jìn)行回歸測試。'
},
{
'name': '開始報表模塊開發(fā)',
'planned_time': '下周三至周五',
'description': '設(shè)計并實現(xiàn)數(shù)據(jù)報表功能,包括數(shù)據(jù)統(tǒng)計和可視化展示。'
},
{
'name': '代碼審查與重構(gòu)',
'planned_time': '下周五',
'description': '對現(xiàn)有代碼進(jìn)行審查,優(yōu)化代碼結(jié)構(gòu)和性能。'
}
],
'issues': [
{
'title': '性能問題',
'description': '在高并發(fā)情況下,系統(tǒng)響應(yīng)速度明顯下降。',
'solution': '計劃通過引入緩存機(jī)制和優(yōu)化數(shù)據(jù)庫查詢來解決。'
},
{
'title': '團(tuán)隊協(xié)作效率',
'description': '當(dāng)前的代碼版本管理流程較為復(fù)雜,影響開發(fā)效率。',
'solution': '建議簡化Git工作流,并加強(qiáng)團(tuán)隊培訓(xùn)。'
}
]
}
# 生成周報
return generate_weekly_report(week_data, f"技術(shù)部周報_{week_data['start_date']}_{week_data['end_date']}.docx")
# 執(zhí)行生成周報
# create_sample_weekly_report()
通過以上代碼示例和應(yīng)用場景,你可以輕松掌握Python Word文檔自動化的各種技巧,大幅提高工作效率。無論是創(chuàng)建簡單的文檔,還是生成復(fù)雜的報告、合同或簡歷,Python都能幫你輕松應(yīng)對。
到此這篇關(guān)于Python實現(xiàn)Word文檔自動化處理操作的文章就介紹到這了,更多相關(guān)Python Word自動化處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在python中使用pymysql往mysql數(shù)據(jù)庫中插入(insert)數(shù)據(jù)實例
今天小編就為大家分享一篇在python中使用pymysql往mysql數(shù)據(jù)庫中插入(insert)數(shù)據(jù)實例。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python 請求服務(wù)器的實現(xiàn)代碼(http請求和https請求)
本篇文章主要介紹了python 請求服務(wù)器的實現(xiàn)代碼(http請求和https請求),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Python中執(zhí)行JavaScript實現(xiàn)數(shù)據(jù)抓取的多種方法
JavaScript是一門強(qiáng)大的腳本語言,廣泛應(yīng)用于網(wǎng)頁前端開發(fā)、構(gòu)建交互式用戶界面以及處理各種客戶端端任務(wù),有時可能需要在Python環(huán)境中執(zhí)行JavaScript代碼,本文將介紹多種方法,幫助你在Python中執(zhí)行 JavaScript代碼,并提供詳盡的示例代碼,使你能夠輕松掌握這一技能2023-11-11
機(jī)器學(xué)習(xí)實戰(zhàn)之knn算法pandas
這篇文章主要為大家詳細(xì)介紹了機(jī)器學(xué)習(xí)實戰(zhàn)之knn算法pandas,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06
Django中QuerySet查詢優(yōu)化之prefetch_related詳解
prefetch_related()和select_related()的設(shè)計目的很相似,都是為了減少SQL查詢的數(shù)量,但是實現(xiàn)的方式不一樣,下面這篇文章主要給大家介紹了關(guān)于Django中QuerySet查詢優(yōu)化之prefetch_related的相關(guān)資料,需要的朋友可以參考下2022-11-11
Python第三方庫qrcode或MyQr生成博客地址二維碼
使用第三方庫qrcode或者M(jìn)yQr給自己的博客網(wǎng)址快速生成二維碼,一鍵分享,文中含有詳細(xì)示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
跟老齊學(xué)Python之永遠(yuǎn)強(qiáng)大的函數(shù)
Python程序中的語句都會組織成函數(shù)的形式。通俗地說,函數(shù)就是完成特定功能的一個語句組,這組語句可以作為一個單位使用,并且給它取一個名字,這樣,我們就可以通過函數(shù)名在程序的不同地方多次執(zhí)行(這通常叫做函數(shù)調(diào)用),卻不需要在所有地方都重復(fù)編寫這些語句。2014-09-09

