把文件夹下所有的excle写入word文件中

把文件夹下所有的excle写入word文件中
python 复制代码
from pathlib import Path, PurePath
from openpyxl import load_workbook
from docx import Document

# 当前目录
p = Path('./')
# 获取所有 xlsx 文件
files = [x for x in p.iterdir() if x.is_file() and PurePath(x).match('*.xlsx')]

# 创建 Word 文档
doc = Document()

for file in files:
    print(f'文件名={file.name}')
    wb = load_workbook(file)
    for sheet_name in wb.sheetnames:
        print(f"工作表名称: {sheet_name}")
        ws = wb[sheet_name]

        # 在 Word 中加标题(文件名 + sheet名)
        doc.add_heading(f"{file.name} - {sheet_name}", level=2)

        # 获取 sheet 所有数据
        data = []
        for row in ws.iter_rows(values_only=True):
            # 如果整行都是空,则跳过
            if all(cell in (None, '') for cell in row):
                continue
            data.append([str(cell) if cell is not None else '' for cell in row])

        if data:
            # 创建 Word 表格
            table = doc.add_table(rows=1, cols=len(data[0]))
            table.style = 'Table Grid'

            # 表头(假如没有表头,这里就只是第一行)
            hdr_cells = table.rows[0].cells
            for idx, val in enumerate(data[0]):
                hdr_cells[idx].text = val

            # 添加数据行
            for row_data in data[1:]:
                row_cells = table.add_row().cells
                for idx, val in enumerate(row_data):
                    row_cells[idx].text = val

            doc.add_paragraph('')  # 分段落空行
        else:
            doc.add_paragraph('(此工作表为空)')

# 保存 Word 文件
output_dir = Path('../word')
output_dir.mkdir(exist_ok=True, parents=True)
output_file = output_dir / 'merged.docx'
doc.save(output_file)

print(f"已将所有 Excel 数据写入 Word 文件: {output_file}")