使用Python,如何快速将Excel文档快速复制到Word中,以下是想用多线程+队列的思想将多个表格生成多个Word,并保存到桌面上,但是程序运行不了,麻烦看下具体是哪里的问题?
import xlrd3 as xlrd
import threading
import queue
from docx import Document,section
from docx.enum.section import WD_ORIENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.shared import Pt,Cm,Inches
def put():
# 读取所选位置表格,并输出行数和列数
path = r"C:\Users\Administrator\Desktop\tav.xlsx"
workbook = xlrd.open_workbook(path)
for sheet_names in workbook.sheet_names():
sht = workbook.sheet_by_name(sheet_names)
nrows = sht.nrows
ncols = sht.ncols
print(sht.name, ':', '共有', nrows, '行', ncols, '列。')
q.put([nrows, ncols])
def get():
while not q.empty():
nrows = q.get()[0]
ncols = q.get()[1]
'''创建一个对应当前sheet行数和列数的Word文档表格'''
document = Document()
'''设置为横向页面,设置页眉'''
section = document.sections[0]
section.page_height = Cm(29.7)
section.page_width = Cm(21)
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
'''创建一个对应当前sheet行数和列数的Word文档表格'''
table = document.add_table(rows=nrows, cols=ncols, style='Table Grid')
document.add_page_break()
'''设置表格居中对齐'''
table.alignment = WD_TABLE_ALIGNMENT.CENTER
'''自动调整列宽以提高单元格内容的适合度'''
table.autofit = True
'''设置表格样式'''
'''设置表格内的字体样式(时代新罗马)'''
table.style.font.name = 'Times New Roman'
'''设置表格内容字体居中'''
for r in range(nrows): # 循环将每一行,每一列都设置为居中
for c in range(ncols):
table.cell(r, c).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(r, c).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
document.save(r'C:\Users\Administrator\Desktop\test' + str(r) + '.doc')
if __name__ == "__main__":
q = queue.Queue(maxsize=20)
t0 = threading.Thread(target=put)
t1 = threading.Thread(target=get)
t2 = threading.Thread(target=get)
t3 = threading.Thread(target=get)
t0.start()
t1.start()
t2.start()
t3.start()