python 实现选择excel相关区域插入到word文件中

from openpyxl import load_workbook
from docx import Document

# 加载Excel文件和Word文件
excel_file = r'C:\Users\Thinkpad\Desktop\资料整编2023110--V6.xlsx'
word_file = r'C:\Users\Thinkpad\Desktop\1.docx'

# 打开Excel文件并选择要插入的区域
wb = load_workbook(excel_file)
ws = wb['水位特征值统计'] # 假设要插入的区域在Sheet1中
data = ws['B1:H26']   # 假设要插入的区域

# 打开Word文件
doc = Document(word_file)

# 在指定位置插入表格
table = doc.add_table(rows=len(data), cols=len(data[0]))

for i, row in enumerate(data):
    for j, cell in enumerate(row):
        table.cell(i, j).text = str(cell.value)

# 保存Word文件
doc.save(r'C:\Users\Thinkpad\Desktop\1.docx')

猜你喜欢

转载自blog.csdn.net/ducanwang/article/details/131481689