#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')
05-24