LoginSignup
1
3

More than 3 years have passed since last update.

PythonでExcel操作【openpyxl - 複数セルの範囲指定】

Last updated at Posted at 2021-03-28

目次

  1. for文で自力で
  2. 左上と右下のセルを指定して
  3. sheet.iter_rows()を利用して
  4. 実践テクニック

Excelファイルの読み込み

import openpyxl as excel
book = excel.load_workbook("excel_filename.xlsx")
sheet = book.active

1.for文で自力で

for y in range(2, 5):
    r = []
    for x in range(2, 5):
        v = sheet.cell(row = y, column = x).value
        r.append(v)
    print(r)

2.左上と右下のセルを指定して

for row in sheet["B2:D4"]:
    print([cell.value for cell in row])

3.sheet.iter_rows()を利用して

for row in sheet.iter_rows(min_row = 2, max_row = 4, min_col = 2, max_col = 4):
    print([cell.value for cell in row])

4.実践テクニック

何行続くかわからない場合は、セルを多めに取得して何かしらでbreak処理等する

rows = sheet["A3": "F999"]
for row in rows:
    values = [cell.value for cell in row]
    if values[0] is None: break
    print(values)
1
3
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
1
3