Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active January 14, 2025 09:43
Show Gist options
  • Save nakagami/ed0203b68b16115b29781902f6eb2f02 to your computer and use it in GitHub Desktop.
Save nakagami/ed0203b68b16115b29781902f6eb2f02 to your computer and use it in GitHub Desktop.
openpyxl を使うサンプル
# openpyxl のサンプル
# Excel の 1シート目の先頭行の内容を読み取る
# 先頭行の値を 2行目に設定
# B セルを削除
# 出来上がった Excel を bytes データに変換
import io
from openpyxl import load_workbook
IN_FILE = "example_in.xlsx"
OUT_FILE = "example_out.xls"
with open(IN_FILE, "rb") as in_file:
in_bytes = in_file.read()
# Excel ファイルを読み込む
# workbook = load_workbook(IN_FILE) と同じ
workbook = load_workbook(io.BytesIO(in_bytes))
# 1シート目を取得
sheet = workbook.worksheets[0]
# sheet = workbook.active でアクティブなシートを取得
# 先頭行を読み取って文字列に変換
first_row = [str(cell.value) for cell in sheet[1]]
print(first_row)
# 先頭行の文字列を2行目に設定
for col_num, cell_value in enumerate(first_row, 1):
sheet.cell(row=2, column=col_num, value=cell_value)
# B列を削除
sheet.delete_cols(2)
# Excelファイルを保存
# workbook.save(OUT_FILE) と同じ
out_bytesio = io.BytesIO()
workbook.save(out_bytesio)
out_bytes = out_bytesio.getvalue()
with open(OUT_FILE, "wb") as out_file:
out_file.write(out_bytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment