LoginSignup
1

More than 3 years have passed since last update.

Python手遊び(Excel to CSV - powered by xlrd)

Posted at

この記事、何?

ついこの前あれこれ投稿した中の一つでExcelからcsvを作りたいというのを書いた。
C#で書いてみたんだけど、悔い改めてPythonで書き直した。

いやぁ・・・だって、すごーーく遅かったんだもの。
たぶん、あとで原因分析やります。トラブルシューティングの事例ということで。

で、Pythonで20行ほど書いておしまい。
しかも、ほとんどはほかの方のコードの流用。。。

いや、いいんだ。Excelからcsvが欲しいということ自体が目的なので。。。

参考資料

■PythonでExcel
https://qiita.com/fukuit/items/f28ae581cd199fc30e0b

仕様を一言

ハードコーディングの対象ファイルのシートを全部csv化する。
(※Tabで区切ったのでtsvといえ、という話もあるかもですが。。。)

出来上がり

import xlrd
import os.path
import numpy as np
xlfile = "test.xlsx"

#テキストファイル出力
def write_text(filepath, lines):
    with open(filepath, 'w', encoding='utf-8') as f:
        for line in lines:
            f.write(line + '\n')

if os.path.exists(xlfile):
    xls = xlrd.open_workbook(xlfile)
    for sheet in xls.sheets():
        nrows = sheet.nrows-1
        ncols = sheet.ncols 
        lines = []
        for r in range(1, nrows+1):
            line = ''
            for c in range(0, ncols):
                line += str(sheet.cell(r,c).value) + '\t'
            lines.append(line)

        write_text(sheet.name, lines)

感想

C#で奮闘したのって何だったんだろうねぇ・・・
ありがとうPython、ありがとうQiita。

参考資料の投稿されたfukuitさん、ありがとうございます!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1