直接上代码
#-*-coding:utf-8 -*-
import docx
import openpyxl
import os
import sys
import re
import subprocess
#import xlwt
import time
from docx import document #导入库
def read_word(wd):
document = document(wd) #读入文件
tables = document.tables #获取文件中的表格集
row_content = []
for table in tables[:]: #i记录表序号
tb_list = []
for row in table.rows[:]: #记录每个表的每一行存储于 row中
list = []
for cell in row.cells[:]: # 读一行中的所有单元格
list.append(cell.text)
tb_list.append(list)
row_content.append(tb_list)
return row_content
def save_excel(tbs,excel_file):
if tbs == []: #源文件无表格,则返回1
return 1
book = openpyxl.Workbook() #先创建一个工作簿
for i,tb in enumerate(tbs[:]): #读每个表数据
sheet = book.create_sheet('sheet' + str(i)) #创建一个test_case的sheet表单
for i,row in enumerate(tb[:]): #读每行数据
for j,cell in enumerate(row[:]): #读每个单元格数据
sheet.cell(i + 1,j + 1, cell)
time.sleep(1)
book.save(excel_file)
return 0
#def save_excel(tb,sheet_nm):
# book = openpyxl.Workbook() #先创建一个工作簿
# sheet = book.create_sheet('sheet' + str(sheet_nm)) #创建一个test_case的sheet表单
# for i,row in enumerate(tb[:]):
# for j,cell in enumerate(row[:]):
# sheet.cell(i + 1,j + 1, cell)
# book.save("C:\Users\Admin\Desktop\dtl_aa.xlsx")
if __name__ == '__main__':
if len(sys.argv) < 3:
print("please put in two argvs.")
sys.exit(1)
docx = sys.argv[1] #word文档名
execl = sys.argv[2] #导出excel文档名
wd = "C:\Users\Admin\Desktop\" + docx
excel_file = "C:\Users\Admin\Desktop\" + execl
tbs = read_word(wd)
if save_excel(tbs,excel_file) == 0:
print("由word[" + docx + "]生成excel文件[" + excel_file + "] !!!")
else:
print("生成文件失败,请检查源文件是否无表格,或其他不明原因。")



