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}")

相关推荐
麦麦鸡腿堡几秒前
Java事件处理机制
java·开发语言·python
谅望者41 分钟前
数据分析笔记07:Python编程语言介绍
大数据·数据库·笔记·python·数据挖掘·数据分析
Geo_V1 小时前
LangChain Memory 使用示例
人工智能·python·chatgpt·langchain·openai·大模型应用·llm 开发
小呀小萝卜儿2 小时前
2025-11-15 学习记录--Python-LSTM模型定义(PyTorch)
python·学习·lstm
百锦再2 小时前
第15章 并发编程
android·java·开发语言·python·rust·django·go
laufing2 小时前
pyinstaller 介绍
python·构建打包
谅望者3 小时前
数据分析笔记09:Python条件语循环
笔记·python·数据分析
Auspemak-Derafru3 小时前
从U盘损坏中恢复视频文件并修复修改日期的完整解决方案
python
techzhi3 小时前
Intellij idea 注释模版
java·python·intellij-idea
李昊哲小课3 小时前
wsl ubuntu24.04 cuda13 cudnn9 pytorch 显卡加速
人工智能·pytorch·python·cuda·cudnn