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

相关推荐
Warson_L11 分钟前
Python 常用内置标准库
python
Warson_L34 分钟前
Python 函数的艺术 (Functions)
python
Warson_L38 分钟前
Python 流程控制与逻辑
后端·python
long_songs40 分钟前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘
必然秃头44 分钟前
Python 环境安装及项目构建指南
python
Warson_L1 小时前
Python 四大组合数据类型 (Collection Types)
后端·python
廋到被风吹走1 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
Warson_L1 小时前
Python 数据类型核心笔记
python
wefly20172 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
胡耀超3 小时前
Token的八副面孔:为什么“词元“不需要更好的翻译,而需要更多的读者
大数据·人工智能·python·agent·token·代币·词元