Python抽取Word表格保存为Excel

只支持docx格式,根据内容过滤指定表格的时候需要加上条件,比如table.rows>1否则遇到只有单行表格table.cell可能会触发list out of range异常

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import docx
from docx import Document
import xlwt;
import xlrd;
import glob

def readdoc(filename):
    doc = Document(filename)
    n = 0
    m = 0
    j = 0
    for table in doc.tables:
        table_temp = []
        table_temp.insert(0,filename)
        if len(table.rows) > 1 and table.cell(1, 0).text.strip() == "输入项名称":
            m = m + 1
            for row in table.rows:
                row_temp = []
                j = j + 1
                for cell in row.cells:
                    row_temp.append(cell.text)
                table_temp.append(row_temp)
            tables.append(table_temp)
        n = n + 1
    print("File name:" + filename + " tables:" + repr(n) + " parsed:" + repr(m))
    return tables

def writeExcel(tables,filename):

    # bold font
    style = xlwt.easyxf('font: bold 1')

    Sheet_index = 0
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('sheet' + str(Sheet_index),cell_overwrite_ok = True)
    Sheet_index = Sheet_index + 1
    j = 0
    for table in tables:
        for rows in table:
            j = j + 1
            r = table.index(rows)
            if r == 0:
                # write filename with style
                worksheet.write(j,0,rows,style)
            else:
                # write table
                for cell in rows:
                    c = rows.index(cell)
                    #print(r,c,cell)
                    worksheet.write(j,c,cell)
    workbook.save(filename[:-5] + ".xls")

filenames = glob.iglob("**/*.docx", recursive=True)
tables = []
for filename in filenames:
    tables = readdoc(filename)

writeExcel(tables,filename)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,495评论 0 13
  • (注1:如果有问题欢迎留言探讨,一起学习!转载请注明出处,喜欢可以点个赞哦!)(注2:更多内容请查看我的目录。) ...
    love丁酥酥阅读 4,245评论 2 5
  • jack徐杰阅读 327评论 0 1
  • (一) 亲爱的月亮, 你在天上, 吸引着我的目光。 . 小月牙儿,那么可爱, 我靠近了山坡, 你躲进了山坡。 . ...
    栗子六壹阅读 1,008评论 0 49
  • 资产是公司拥有的并且可以适用进而创造更多财产的资源。 公司的资产包括现金、银行存款、厂房、设备、投资收益等。 资产...
    snailwww阅读 190评论 1 4