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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据服务生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值