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

相关推荐
l1t8 小时前
JIT执行python脚本的工具codon安装和测试
开发语言·python
2501_901006478 小时前
Golang怎么用gRPC Gateway_Golang gRPC Gateway教程【经典】
jvm·数据库·python
2501_901200538 小时前
golang如何实现错误预算Error Budget计算_golang错误预算Error Budget计算实现实战
jvm·数据库·python
2401_867623989 小时前
如何解决OUI图形界面无法调用_xhost与DISPLAY变量设置
jvm·数据库·python
Dxy12393102169 小时前
Python 去除 HTML 标签获取纯文本
开发语言·python·html
2401_824697669 小时前
CSS如何实现元素反转特效_使用transform-scaleX(-1)操作
jvm·数据库·python
CLX05059 小时前
如何在 WordPress AMP 网站中为特定模板禁用 AMP 渲染
jvm·数据库·python
砚底藏山河9 小时前
python、JavaScript 、JAVA,定制化数据服务,助力业务高效落地
java·javascript·python
神明9319 小时前
如何实现SQL动态字段选择查询_利用反射或动态拼接字符串
jvm·数据库·python
洛的地理研学9 小时前
Python下载并处理MOD13A3植被指数数据
开发语言·python