python把excel中的内容复制到word里

#coding=utf8


from docx import Document

# 创建新文档
from docx.enum.section import WD_ORIENT, WD_ORIENTATION

# # # 添加标题
# # doc.add_heading('Python-docx 示例', level=1)
# #
# # # 添加段落
# # doc.add_paragraph('这是一个示例文档。')
# document = Document('2.docx')
# section = document.sections[0]
# new_width, new_height = section.page_height, section.page_width
# section.orientation = WD_ORIENT.LANDSCAPE
# section.page_width = new_width
# section.page_height = new_height
# # 保存文档
# document.save('示例文档.docx')
from docx.shared import Cm
# -*- coding:UTF-8 -*-
from random import choice
from docx import Document
from openpyxl import load_workbook

def xlsx2docx(fn):
    #打开excel文件,如有公式,读取公式计算结果
    wb=load_workbook(fn,data_only=True)
    #创建空白word 文件
    document=Document()
    #查看所有可用的表格样式
    # table_styles=[style for style in document.styles
    #             if style.type==WD_STYLE_TYPE.TABLE]
    #print(talbe_styles)

    #遍历EXCEL 文件中所有的worksheet
    for ws in wb.worksheets:
        rows=list(ws.rows)
        #增加段落,也就是表格的名称
        document.add_paragraph(ws.title)
        #根据worKsheet的行数和列数,在word 文件中创建核实大小的表格
        table=document.add_table(rows=len(rows),cols=len(rows[0]))
                                # style=choice(table_styles))
        #从worksheet读取数据,写入word文件中的表格
        for  irow,row in enumerate(rows):
            for icol,col in enumerate(row):
                table.cell(irow,icol).text=str(col.value)
    #保存word文件
    section = document.sections[0]
    new_width, new_height = section.page_height, section.page_width
    section.orientation = WD_ORIENTATION.LANDSCAPE
    section.page_width = Cm(29.7)
    section.page_height = Cm(42)
    document.save(fn[:-4]+'docx')
#调用函数,进行数据导入
xlsx2docx('22.xlsx')
# 存储位置
# document.save('00001.docx')

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农村落魄小青年

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

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

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

打赏作者

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

抵扣说明:

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

余额充值