久しぶりのPythonネタです。久しぶりにPerlとかPythonを触っていて、ふとWORD中の表をExcelに一括変換したくなったのでやってみました。
ソースコード
とりあえず何はなくともソースコードです。まあ、単純ではあるのですがRowとColumnを逆に長い間考えていました。doc.talbesでTable一覧が取得できるんですね。
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import docx import openpyxl def docx2csv(input,output): doc = docx.Document(input) wb = openpyxl.Workbook() sheet = wb.active f = open(output, 'w', encoding ='UTF-8') r_start=0; for table in doc.tables: rlen = len(table.rows) clen = len(table.columns) for r in range(0,rlen): for c in range(0,clen): sheet.cell(column=c+1,row=r_start+r+1).value = table.cell(r,c).text r_start=r_start+rlen+1 wb.save(output) input = sys.argv[1] output = sys.argv[2] docx2csv(input,output)
コマンド実行
下記の様に実行します
>python docs2csv.py InvestmentTrust.docx InvestmentTrust.xlsx
結果
結果としては、下記の様なWORDのファイル(この後にもう2つ表が続いています)が
下記の様なEXCELになりました。
これをベースとして、WORDの中のTable情報を抜き出し&変換して、EXCELのグラフに変換できそうです。更にEXCELから目的の形式にPerlで変換するのですが・・・
それはさておき、日経のページから適当なランキングを持ってきてWordのTableを作ったのですが、名前を聞かない投資信託ばかりですね(^^;
コメント