LoginSignup
1
1

More than 1 year has passed since last update.

Pythonでエクセルに二次元配列を書き込む

Last updated at Posted at 2022-06-28

Pythonを使って99×99の掛け算をエクセルに書き込んでみる
今回は2パターン示す

環境

  • OS
    • Windows10
  • Python
    • Python3.9.6
  • Excel
    • Microsoft 365

準備

今回はwin32comでエクセルに対して操作を行うため、pywin32のインストールを行う

pipのアップグレード

pip install --upgrade pip

pywin32のインストール

pip install pywin32

実装

99×99の二次元配列を用意する
sample.xlsxを開いて、Sheet1を取得する

from pathlib import Path
import win32com.client

# 99×99の二次元配列
twoDArray = [[i * j for i in range(1, 100)] for j in range(1, 100)]

# エクセルを開く
app = win32com.client.Dispatch("Excel.Application")
abspath = str(Path(r"sample.xlsx").resolve())
book = app.Workbooks.Open(abspath)
sheet = book.Worksheets("Sheet1")

パターン1(ループで頑張る)

セルの始まりは(0,0)ではなく(1,1)であるため、インデックスに+1している

for y, array in enumerate(twoDArray):
    for x, element in enumerate(array):
        sheet.Cells(y+1, x+1).Value = twoDArray[y][x]

パターン2(一括で貼り付ける)

99×99の範囲に値を張り付ける

sheet.Range(sheet.Cells(1,1),
            sheet.Cells(len(twoDArray),
                        len(twoDArray[0]))
            ).Value = twoDArray

結果

パターン1,2で結果は変わりません
99×99の二次元配列が書き込まれます
image.png

速度

それぞれのパターンにおける値書込みの実行時間を比較する(10回平均)

  • パターン1
    • 42.97[sec]
  • パターン2
    • 0.046[sec]

結論

ループで処理しない分、圧倒的にパターン2が早いですね

参考

Python pywin32(win32com) Excel 操作備忘録
Excel using win32com and python

1
1
3

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
1