4
4

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 3 years have passed since last update.

【Python】Workbook.copy_worksheetメソッドを使用してシートをコピーする。

Last updated at Posted at 2021-02-07

pythonを使用してExcelファイルの操作を勉強しています。
本日の気づき(復習)は、シートのコピーに関してです。
pythonでExcelを操作するため、openpyxlというパッケージを使用しています。

「原紙」と言う名前のシートを持つブック「議事録」があり、当日分のシートを作成したいとします。

Workbook.copy_worksheetメソッド

wb.copy_worksheet(シート)

渡すのはシート名ではなくて、オブジェクトです。
また、シート名は当日の日付を記述したいのでPythonの標準ライブラリであるdatetimeのdate.todayメソッドを使用します。

copy_sheet.py
from datetime import date
from openpyxl import load_workbook

wb = load_workbook('議事録.xlsx')

# シートの選択を解除
for ws in wb.worksheets:
    ws.sheet_view.tabSelected = None

# 「原紙」のシートを取得
ws_template = wb['原紙']

# シートをコピー
ws_copy = wb.copy_worksheet(ws_template)

# 当日の日付を取得
today = date.today()

# シート名を当日日付にする
ws_copy.title = f'{today:%Y年%m月%d日}'

# シートを先頭へ移動
wb.move_sheet(ws_copy, offset=-wb.index(ws_copy))

# 先頭のシートを再度選択状態にする
wb.active = 0

# ブック名を変更して保存
wb.save('議事録_変更後.xlsx')

日付の記入って地味に手間なので自動化できると後々楽になりますね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?