5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでExcelの新規ファイルを作成し、計算用ドリルを書き込む

Last updated at Posted at 2019-01-30

下記のQiita記事のコメント参考用に。

プログラミング未経験者がPython覚えて子ども用計算ドリルを作る


"""計算練習ドリルを作成(新規ブック作成版)
"""

import random
import openpyxl

wb = openpyxl.Workbook()  #新規ワークブックを作成
sheet = wb.active
list_ = [[a, b] for a in range(1, 10) for b in range(1, 10)]
random.shuffle(list_)

for n, v in enumerate(list_):
	x, y = n // 6, n % 6    # 座標変換1 (碁盤タイプ) 
	r, c = x+3 , y*6+1      # 座標変換2【(r,c】各計算式左上座標)
	sheet.cell(row=r, column=c, value=v[0])
	sheet.cell(row=r, column=c + 1, value='+')
	sheet.cell(row=r, column=c + 2, value=v[1])
	sheet.cell(row=r, column=c + 3, value='=')
	print(n,(x,y),(r,c),v)  #参考に座標変換内容表示
wb.save('output.xlsx')

drill_img.JPG

さらに一気に保存するバージョン(colab)


"""計算練習ドリルを作成
    改行処理にバッファー活用+appendで行ごと書き込むバージョン
"""

import random
import openpyxl

wb = openpyxl.Workbook()  #新規ワークブックを作成
sheet = wb.active

# 各計算式を一つのListとして取り扱うと理解しやすい
list_ = [[a, '+', b, '=', ''] for a in range(1, 10) for b in range(1, 10)]

random.shuffle(list_)

buf = []    #dataを一時ため込む変数
for v in list_:
    if len(buf) > 25: #一行に25列以上データがある場合は改行    
        sheet.append(buf)
        buf=[]
    buf.extend(v)     #buf内にデータを一時的に追加保存
sheet.append(buf)     #最終行書き込み

wb.save('output3.xlsx')

5
10
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
5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?