Search Posts

Visits: 341

久しぶりにExcelでプログラムを試作。
15年くらい前はVBAしか開発環境がなく、マクロで開発すると自分でも維持管理できなくなってしまうので遠ざかっていたが、Pythonで大規模データ処理にも使えるということなので再度試行してみる。
今回は、環境設定と確認。これから大量の帳簿や伝票データ処理を試行予定。

Excel PowerPivoy Addin有効化

Power Pivotを初めて使う場合の手順 アドイン(追加)する方法(初期設定)を参考に有効化。
ファイル オプション アドイン で表示される画面から先の操作で戸惑ってしまった。
画面の下にある

管理(A):でCOMアドインを選択して設定ボタンを押すと追加選択可能になった。

Python3インストール

NumPy、pandas、Matplotlib をpipでインストールする方法を参考にインストール。Anacondaで環境構築する例が多いができるだけ単純にしたいのでpyとpipでインストール。python-3.10.2-amd64.exeをPython 3.10.2ダウンロードページからダウンロード。pyが標準ではインストールされないのでpython-3.10.2-amd64.exeを再実行してModifyする際に組み込み指定した。

pip更新

PS C:\Users\xxx> py -m pip install -U pip
Requirement already satisfied: pip in c:\users\xxx\appdata\local\programs\python\python310\lib\site-packages (21.2.4)
Collecting pip
  Downloading pip-22.0.3-py3-none-any.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 6.4 MB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 21.2.4
    Uninstalling pip-21.2.4:
      Successfully uninstalled pip-21.2.4
Successfully installed pip-22.0.3

numpyインストール

PS C:\Users\xxx> py -m pip install numpy
Collecting numpy
  Downloading numpy-1.22.2-cp310-cp310-win_amd64.whl (14.7 MB)
     ---------------------------------------- 14.7/14.7 MB 7.4 MB/s eta 0:00:00
Installing collected packages: numpy
Successfully installed numpy-1.22.2

pandasインストール

PS C:\Users\xxx> py -m pip install pandas
Collecting pandas
  Downloading pandas-1.4.1-cp310-cp310-win_amd64.whl (10.6 MB)
     ---------------------------------------- 10.6/10.6 MB 8.5 MB/s eta 0:00:00
Collecting python-dateutil>=2.8.1
  Downloading python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
     ---------------------------------------- 247.7/247.7 KB 7.4 MB/s eta 0:00:00
Requirement already satisfied: numpy>=1.21.0 in c:\users\xxx\appdata\local\programs\python\python310\lib\site-packages (from pandas) (1.22.2)
Collecting pytz>=2020.1
  Downloading pytz-2021.3-py2.py3-none-any.whl (503 kB)
     ---------------------------------------- 503.5/503.5 KB 6.2 MB/s eta 0:00:00
Collecting six>=1.5
  Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: pytz, six, python-dateutil, pandas
Successfully installed pandas-1.4.1 python-dateutil-2.8.2 pytz-2021.3 six-1.16.0

matplotlibインストール

PS C:\Users\xxx>  py -m pip install matplotlib
Collecting matplotlib
  Downloading matplotlib-3.5.1-cp310-cp310-win_amd64.whl (7.2 MB)
     ---------------------------------------- 7.2/7.2 MB 8.5 MB/s eta 0:00:00
Collecting fonttools>=4.22.0
  Downloading fonttools-4.29.1-py3-none-any.whl (895 kB)
     ---------------------------------------- 895.5/895.5 KB 8.1 MB/s eta 0:00:00
Collecting pyparsing>=2.2.1
  Downloading pyparsing-3.0.7-py3-none-any.whl (98 kB)
     ---------------------------------------- 98.0/98.0 KB 5.5 MB/s eta 0:00:00
Collecting packaging>=20.0
  Downloading packaging-21.3-py3-none-any.whl (40 kB)
     ---------------------------------------- 40.8/40.8 KB 1.9 MB/s eta 0:00:00
Collecting kiwisolver>=1.0.1
  Downloading kiwisolver-1.3.2-cp310-cp310-win_amd64.whl (52 kB)
     ---------------------------------------- 52.1/52.1 KB 2.8 MB/s eta 0:00:00
Requirement already satisfied: python-dateutil>=2.7 in c:\users\xxx\appdata\local\programs\python\python310\lib\site-packages (from matplotlib) (2.8.2)
Collecting cycler>=0.10
  Downloading cycler-0.11.0-py3-none-any.whl (6.4 kB)
Collecting pillow>=6.2.0
  Downloading Pillow-9.0.1-cp310-cp310-win_amd64.whl (3.2 MB)
     ---------------------------------------- 3.2/3.2 MB 8.3 MB/s eta 0:00:00
Requirement already satisfied: numpy>=1.17 in c:\users\xxx\appdata\local\programs\python\python310\lib\site-packages (from matplotlib) (1.22.2)
Requirement already satisfied: six>=1.5 in c:\users\xxx\appdata\local\programs\python\python310\lib\site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
Installing collected packages: pyparsing, pillow, kiwisolver, fonttools, cycler, packaging, matplotlib
Successfully installed cycler-0.11.0 fonttools-4.29.1 kiwisolver-1.3.2 matplotlib-3.5.1 packaging-21.3 pillow-9.0.1 pyparsing-3.0.7

openpyxlインストール

PS C:\Users\xxx> py -m pip install openpyxl
Collecting openpyxl
  Downloading openpyxl-3.0.9-py2.py3-none-any.whl (242 kB)
     ---------------------------------------- 242.2/242.2 KB 7.5 MB/s eta 0:00:00
Collecting et-xmlfile
  Downloading et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)
Installing collected packages: et-xmlfile, openpyxl
Successfully installed et-xmlfile-1.1.0 openpyxl-3.0.9
PS C:\Users\nobuy> py -m pip install xlrd
Collecting xlrd
  Downloading xlrd-2.0.1-py2.py3-none-any.whl (96 kB)
     ---------------------------------------- 96.5/96.5 KB 2.7 MB/s eta 0:00:00
Installing collected packages: xlrd
Successfully installed xlrd-2.0.1
PS C:\Users\xxx>

Excelファイル出力とピボットテーブル作成

Qiitaの記事を参考にした。
Python から Excel を編集し、ピボットテーブルを作成する

PS C:\Users\xxx\Labo> Python
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> import random
>>> from datetime import datetime as dt
>>>
>>> record = []
>>> for y in range(2015, 2020):
...     for m in range(1, 13):
...         for shop in ['A', 'B', 'C']:
...             date = dt(year=y, month=m, day=1).strftime('%Y-%m-%d')
...             price = 200 + random.randint(0,100)
...             record.append([date, shop, price])
...
>>> df_record = pd.DataFrame(record)
>>> df_record.columns = ['date', 'shop', 'price']
>>> df_record['date'] = pd.to_datetime(df_record['date'])
>>> df_record.to_excel('testdata.xlsx', index=None)

記事の記述に従ってコマンドを投入してゆくとwin32がないとのメッセージ。準備してないので当然なので調査。

>>> import win32com.client as win32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'win32com'
>>> import os
>>> win32c = win32.constants
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'win32' is not defined
>>>

win32インストール

https://www.kkaneko.jp/data/gen/excelimport.htmlを参考にした。

PS C:\Users\xxx\Labo> pip install -U wheel pywin32
Collecting wheel
  Downloading wheel-0.37.1-py2.py3-none-any.whl (35 kB)
Collecting pywin32
  Downloading pywin32-303-cp310-cp310-win_amd64.whl (9.2 MB)
     ---------------------------------------- 9.2/9.2 MB 7.2 MB/s eta 0:00:00
Installing collected packages: pywin32, wheel
Successfully installed pywin32-303 wheel-0.37.1
PS C:\Users\xxx\Labo>

再度実行

excel = win32.gencache.EnsureDispatch('testdata.xlsx') でエラー。

PS C:\Users\xxx\Labo> Python
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import win32com.client as win32
>>> import os
>>> win32c = win32.constants
>>>
>>> excel = win32.gencache.EnsureDispatch('testdata.xlsx')
Traceback (most recent call last):
  File "C:\Users\nobuy\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221005, 'クラス文字列が無効です', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\nobuy\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\gencache.py", line 618, in EnsureDispatch
    disp = win32com.client.Dispatch(prog_id)
  File "C:\Users\nobuy\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "C:\Users\nobuy\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Users\nobuy\AppData\Local\Programs\Python\Python310\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221005, 'クラス文字列が無効です', None, None)
>>>

PowerShellでPythonを対話実行していたことが原因のようなので、Visual Studio Codeでpythonプログラムファイルをデバッグ実行したところ、Sheet1のデータからpivotシートが作成された。