LoginSignup
0
0

More than 3 years have passed since last update.

Microsoft Excelのセルの値を取得するPythonスクリプトを作成してみた

Last updated at Posted at 2020-12-15

1. MSYS2のインストール

https://www.msys2.org/ からMSYS2の最新版をダウンロードし、Windows 10上にインストールする。
msys2.png

2. Pythonとopenpyxlのインストール

スタートメニュから「SYS2 64bit」-「MSYS2 MinGW 64-bit」を起動し、以下を実行する。

# pacman -Qe
# yes | pacman -S mingw-w64-x86_64-python mingw-w64-x86_64-python-openpyxl
# pacman -Qe

3. スクリプトの作成

excellsp.py
#!/usr/bin/env python3

import sys
import getopt
import openpyxl

def usage():
    print('usage: ' + sys.argv[0] + \
        ' [ -h -q quotation -s separator ] workbook worksheet [celladdr...]', \
        file=sys.stderr)

try:
    opts,argv = getopt.getopt(sys.argv[1:], "hq:s:")
except getopt.GetoptError as err:
    print(err)
    usage()
    sys.exit(1)

separator = '\n'
quotation = ''

for opt,optarg in opts:
    if opt == "-h":
        usage()
        print("Pass2")
        sys.exit()
    elif opt == '-q':
        quotation = optarg
    elif opt == '-s':
        separator = optarg
    else:
        print("Pass1")
        usage()
        sys.exit(1)

if len(argv) < 2:
    usage()
    sys.exit(1)

wb = openpyxl.load_workbook(argv[0])
ws = wb[argv[1]]
del argv[:2]

separator = separator.replace('\\t', '\t').replace('\\n', '\n')
output = ''

for arg in argv:
    value = str(ws[arg].value);
    if quotation != '':
        value = quotation + value.replace(quotation, quotation + quotation) + \
            quotation;
    if output != '':
        output += separator
    output += value

print(output)

4. テスト用ブックの作成

Microsoft Excelで以下の内容のシート「Sheet1」を持つブック「Book1.xlsx」を作成する。

A B C D E
1 a1 b1 c1 d1
2 a2 b2 c2 d2
3 a3 b3 c3 d"3
4 a4 b4 c4 d4

5. スクリプトの実行

# chmod a+x excellsp.py
# ./excellsp.py -h
usage: ./excellsp.py [ -h -q quotation -s separator ] workbook worksheet [celladdr...]
# ./excellsp.py Book1.xlsx Sheet1 A1 C2 D3 E4
a1
c2
d"3
e4
# ./excellsp.py -s '\t' Book1.xlsx Sheet1 A1 C2 D3 E4
a1  c2  d"3 e4
# ./excellsp.py -q '"' -s '\t' Book1.xlsx Sheet1 A1 C2 D3 E4
"a1"    "c2"    "d""3"  "e4"
0
0
0

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
0
0