简介:本文聚焦Python对docx文件表格和文字的高效处理,提供实用代码示例与操作建议,助力开发者提升文档自动化处理能力。
在自动化办公场景中,Python对Word文档(.docx格式)的精准操作已成为提升效率的关键技术。本文将深入探讨如何使用Python的python-docx库实现表格数据的增删改查、文字内容的批量替换与样式调整,并提供完整的代码示例与最佳实践建议。
python-docx是处理.docx文件的专用库,其核心优势在于:
安装命令:
pip install python-docx
from docx import Document# 创建新文档doc = Document()# 添加3行4列的表格table = doc.add_table(rows=3, cols=4)# 设置表格样式(可选)table.style = 'Table Grid' # 带边框的表格样式# 填充表头header_cells = table.rows[0].cellsheader_cells[0].text = '序号'header_cells[1].text = '姓名'header_cells[2].text = '部门'header_cells[3].text = '薪资'# 填充数据行data_rows = [[1, '张三', '技术部', '15000'],[2, '李四', '市场部', '12000']]for i, row_data in enumerate(data_rows, start=1):row_cells = table.rows[i].cellsfor j, value in enumerate(row_data):row_cells[j].text = str(value)doc.save('employee_table.docx')
合并单元格示例:
# 合并第二行的第2-3列table.cell(1, 1).merge(table.cell(1, 2))table.cell(1, 1).text = '合并单元格'
动态添加行:
# 在表格末尾添加新行new_row = table.add_row()new_row.cells[0].text = '3'new_row.cells[1].text = '王五'
def extract_table_data(doc_path):doc = Document(doc_path)tables = doc.tablesextracted_data = []for table in tables:table_data = []for row in table.rows:row_data = [cell.text for cell in row.cells]table_data.append(row_data)extracted_data.append(table_data)return extracted_datadata = extract_table_data('employee_table.docx')print(data)
from docx.shared import RGBColordef process_document(input_path, output_path):doc = Document(input_path)# 文字替换for paragraph in doc.paragraphs:if '旧文本' in paragraph.text:paragraph.text = paragraph.text.replace('旧文本', '新文本')# 样式调整for paragraph in doc.paragraphs:if '重点内容' in paragraph.text:run = paragraph.runs[0]run.font.bold = Truerun.font.color.rgb = RGBColor(255, 0, 0) # 红色run.font.size = Pt(14) # 需要导入:from docx.shared import Ptdoc.save(output_path)
添加带样式的段落:
doc = Document()p = doc.add_paragraph()run = p.add_run('这是加粗红色文字')run.bold = Truerun.font.color.rgb = RGBColor(255, 0, 0)# 设置段落对齐方式from docx.enum.text import WD_ALIGN_PARAGRAPHp.alignment = WD_ALIGN_PARAGRAPH.CENTER
def safe_process(input_path, output_path):try:doc = Document(input_path)# 处理逻辑...doc.save(output_path)except Exception as e:print(f"处理失败: {str(e)}")finally:# 显式关闭(python-docx无直接close方法,但可重新赋值)doc = None
def apply_style(doc, paragraph, style_name):"""应用预定义样式"""if style_name in doc.styles:paragraph.style = doc.styles[style_name]else:# 创建新样式style = doc.styles.add_style(style_name, 1) # 1表示段落样式style.font.name = '微软雅黑'style.font.size = Pt(12)paragraph.style = style
现象:表格内容显示错位
解决方案:
# 设置表格对齐方式from docx.enum.table import WD_TABLE_ALIGNMENTtable.alignment = WD_TABLE_ALIGNMENT.CENTER# 设置单元格垂直对齐cell = table.cell(0, 0)cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER # 需要导入
现象:中文显示为乱码
原因:文档可能包含特殊编码
解决方案:
# 使用二进制模式读取(处理特殊编码)with open('input.docx', 'rb') as f:doc = Document(f)
import pandas as pddef generate_report(data_path, template_path, output_path):# 读取Excel数据df = pd.read_excel(data_path)# 加载模板doc = Document(template_path)# 替换表格数据table = doc.tables[0]for i in range(len(df)):if i < len(table.rows)-1: # 跳过表头row = table.rows[i+1]row.cells[0].text = str(df.iloc[i, 0]) # 第一列row.cells[1].text = str(df.iloc[i, 1]) # 第二列doc.save(output_path)
def merge_documents(templates, output_path):merged_doc = Document()for template in templates:sub_doc = Document(template)# 复制所有段落for para in sub_doc.paragraphs:merged_doc.add_paragraph(para.text, para.style)# 复制表格(简化示例)for table in sub_doc.tables:new_table = merged_doc.add_table(rows=table.rows, cols=table.columns)# 实际实现需要更复杂的单元格复制逻辑merged_doc.save(output_path)
| 操作类型 | python-docx | 替代方案(如win32com) | 适用场景 |
|---|---|---|---|
| 简单表格修改 | ★★★★★ | ★★☆☆☆ | 跨平台需求 |
| 复杂格式保留 | ★★★★☆ | ★★★★★ | 需要精确控制格式时 |
| 大文件处理 | ★★★☆☆ | ★★★★☆ | 处理超大型文档时 |
| 无GUI环境 | ★★★★★ | ❌不可用 | 服务器端自动化处理 |
选型建议:
Python对docx文件的操作已从基础功能发展到企业级应用阶段。通过合理运用表格操作、文字处理和样式管理技术,开发者可以构建高效的文档自动化系统。建议读者从简单案例入手,逐步掌握高级特性,最终实现复杂文档的智能化处理。
完整代码示例和进阶技巧可参考官方文档:https://python-docx.readthedocs.io/en/latest/