0
5

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でExcel操作【openpyxl - 基礎まとめ】

Last updated at Posted at 2021-03-28

インポート

import openpyxl as excel

ワークブック作成 or 読み込み

# 新規ワークブック
book = excel.Workbook()
# 作成済みファイルを読み込み
book = excel.load_workbook("excel_filename.xlsx")
# 計算式ではなく値を取得する
book = excel.load_workbook("excel_filename.xlsx", data_only = True)

シートの指定や操作

# アクティブなワークシート
sheet = book.active
# インデックスで指定
sheet = book.worksheets[シート番号]
# シート名で指定
sheet = book["sheetname"]
# シート名一覧
print(book.sheetnames)
# 新規シート作成
sheet = book.create_sheet(title = "sheetname")
# 既存のシートをコピーして複製
sheet = book.copy_worksheet(book["sheetname"])
# シート名を変更する
sheet.title = "sheetname"
# シートを削除
book.remove(book["sheetname"])

セルの値へのアクセス方法三つ

# セル名で指定
sheet["A1"] = "cell_value"
# 引数で指定
sheet.cell(row = 2, column = 1, value = "cell_value")
# または
cell = sheet.cell(row = 3, column = 1)
cell.value = "cell_value"

セル名の取得、行と列番号の取得

# セル名の取得
cell = sheet.cell(row = 2, column = 3)
print(cell.coordinate)
# 行・列番号の取得
cell = sheet["C2"]
(row, col) = (cell.row, cell.column)

保存

book.save("excel_filename.xlsx")
0
5
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
0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?