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

相关推荐
Csvn11 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch891812 小时前
Python主流框架全解析
开发语言·python
sg_knight12 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财12 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40812 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339912 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz13 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据13 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby13 小时前
springboot读取配置文件
后端·python·flask
阿Y加油吧13 小时前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python