python批量读取Excel数据写入word

from docx import Document

from docx.shared import Pt

from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ROW_HEIGHT_RULE

import os

import pandas as pd

from docx import Document

from docx.oxml.ns import qn

from docx.shared import Pt

... 其他代码 ...

work_dir = 'path_to_your_excel_files'

excel_files = [f for f in os.listdir(

work_dir) if f.endswith(('.xlsx', '.xls'))]

创建一个新的Word文档

doc = Document()

遍历所有Excel文件

for excel_file in excel_files:

... 读取Excel文件并创建Word表格的代码 ...

excel_path = os.path.join(work_dir, excel_file)

读取Excel文件

df = pd.read_excel(excel_path)

将DataFrame转换为Word表格

for _, row in df.iterrows():

table = doc.add_table(rows=1, cols=len(row), style='Table Grid')

添加行并设置单元格数据

for i, value in enumerate(row):

cell = table.cell(0, i)

cell.text = str(value)

cell.vertical_alignment = 'center' # 垂直居中对齐

设置表格样式

table.alignment = WD_TABLE_ALIGNMENT.CENTER

设置行高

for row in table.rows:

row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

row.height = Pt(20)

保存Word文档

... 保存文档的代码 ...

output_path = os.path.join(work_dir, 'CombinedTables.docx')

doc.save(output_path)

print(f"Word文档已保存至:{output_path}")

相关推荐
QQ2422199791 小时前
基于python+微信小程序的家教管理系统_mh3j9
开发语言·python·微信小程序
RSTJ_16252 小时前
PYTHON+AI LLM DAY THREETY-SEVEN
开发语言·人工智能·python
郝学胜-神的一滴2 小时前
深度学习优化核心:梯度下降与网络训练全解析
数据结构·人工智能·python·深度学习·算法·机器学习
Aision_2 小时前
Agent 为什么需要 Checkpoint?
人工智能·python·gpt·langchain·prompt·aigc·agi
清水白石0082 小时前
《Python性能深潜:从对象分配开销到“小对象风暴”的破解之道(含实战与最佳实践)》
开发语言·python
Land03293 小时前
RPA工具选型技术指南:架构差异与实测数据
python·自动化·rpa
kafei_*3 小时前
VScode 添加 UV虚拟环境方法
vscode·python·uv
洛_尘4 小时前
Python 5:使用库
java·前端·python
m0_596749094 小时前
如何防止SQL拼接漏洞_使用PDO对象实现安全的SQL交互
jvm·数据库·python
AIFQuant6 小时前
2026 全球股票/外汇/贵金属行情 API 深度对比:延迟、覆盖、价格与稳定性
python·websocket·ai·金融·mcp