Python編程從0到1(實戰(zhàn)篇:提取Word表格存儲到Excel)

今天突然有一個需求,要把統(tǒng)計局網(wǎng)站下載的Word文檔里的表格提取出來,放到Excel表中,便于下一步進行數(shù)據(jù)分析。

1. 引入擴展庫

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

2. 讀取Word文檔中的表格

def readdoc(filename):    
    doc = docx.Document(filename)
    tables = []
    for table in doc.tables:
        table_temp = []
        for row in table.rows:
            row_temp = []
            for cell in row.cells:
                row_temp.append(cell.text)
            table_temp.append(row_temp)
        tables.append(table_temp)
    return tables

3. 寫入Excel文件

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

4. 遍歷目錄下所有docx文件,并生成同名Excel文件

filenames = glob.glob("jtdoc/*.docx")
for filename in filenames:
    tables = readdoc(filename)
    writeExcel(tables,filename)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容