栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实现从word导出表格到excel小记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python实现从word导出表格到excel小记

直接上代码

#-*-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("生成文件失败,请检查源文件是否无表格,或其他不明原因。")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/268602.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号