programing

특정 컬럼 openpyxl의 모든 행을 반복하다

mailnote 2023. 4. 21. 21:10
반응형

특정 컬럼 openpyxl의 모든 행을 반복하다

openpyxl을 사용하여 지정된 열의 모든 행을 반복하는 방법을 이해할 수 없습니다.

"C" 열의 모든 행에 대한 모든 셀 값을 인쇄하려고 합니다.

현재 저는 다음을 가지고 있습니다.

from openpyxl import workbook
path = 'C:/workbook.xlsx'
wb = load_workbook(filename = path)
ws=wb.get_sheet_by_name('Sheet3')

for row in ws.iter_rows():
    for cell in row:
        if column == 'C':
            print cell.value

C열(버전 2.4.7):

for cell in ws['C']:
   print cell.value

를 사용하여 반복할 범위를 지정할 수 있습니다.

import openpyxl

wb = openpyxl.load_workbook('C:/workbook.xlsx')
ws = wb['Sheet3']
for row in ws.iter_rows('C{}:C{}'.format(ws.min_row,ws.max_row)):
    for cell in row:
        print cell.value

편집: 코멘트에 따라 셀 값을 목록으로 지정합니다.

import openpyxl

wb = openpyxl.load_workbook('c:/_twd/2016-06-23_xlrd_xlwt/input.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
mylist = []
for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
    for cell in row:
        mylist.append(cell.value)
print mylist 

이것도 할 수 있어요.

for row in ws.iter_rows():
   print(row[2].value)

이 경우 여전히 행(셀은 제외)을 반복하고 열 C의 값만 꺼내 인쇄합니다.

위의 솔루션 중 일부는 제대로 작동하지 않습니다(최신 버전의 'openpyxl' 때문일 수 있습니다).여러 가지를 시도해 본 후, 다음과 같이 했습니다.

모든 행과 모든 열 인쇄:

import openpyxl

sheet = openpyxl.load_workbook('myworkbook.xlsx')['Sheet1']
# Iterating through All rows with all columns...
for i in range(1, sheet.max_row+1):
    row = [cell.value for cell in sheet[i]] # sheet[n] gives nth row (list of cells)
    print(row) # list of cell values of this row

모든 행에 특정 열(예: 'E'에서 'L'):

# For example we need column 'E' to column 'L'
start_col = 4 # 'E' column index
end_col = 11 # 'L' column index
for i in range(1, sheet.max_row+1):
    row = [cell.value for cell in sheet[i][start_col:end_col+1]]
    print(row) # list of cell values of this row

다음 점에 유의해 주십시오.

  • sheet[N]은 N번째 행의 '' 개체 목록을 제공합니다(N은 1부터 시작하는 숫자입니다).
  • 행의 첫 번째 열 셀을 가져오려면 sheet[N][0]사용합니다.(시트[N]는 0부터 색인화할 수 있는 '태플'이기 때문입니다).

다음과 같은 경우가 있습니다.

import openpyxl
path = 'C:/workbook.xlsx'
# since is a print, read_only is useful for making it faster.
wb = openpyxl.load_workbook(filename = path, read_only=True)
# by sheet name 
ws=wb['Sheet3']

# non-Excel notation is col 'A' = 1, col 'B' = 2, col 'C' = 3.
# from row = 1 (openpyxl sheets starts at 1, not 0) to no max
for row in ws.iter_cols(min_row=1, min_col=3, max_col=3): 
    # for each row there is one cell object (since min_col = max_col)
    for cell in row:
        # so we print the value
        print(f'C{row}: ', cell.value)

이렇게 해요.내가 뭘 하고 있는지는 모르겠지만 가치 없는 세포는 피한다.

from openpyxl import load_workbook
wb = load_workbook(filename = 'exelfile.xlsx')
ws = wb['sheet1']

for col in ws['A']:
    print (col.value)

셀 객체의 좌표 특성을 사용할 수 있습니다.

좌표 속성에 문자열 형식의 셀 주소가 포함되어 있습니다.

예를들면,

from openpyxl import workbook
path = 'C:/workbook.xlsx'
wb = load_workbook(filename = path)
ws=wb.get_sheet_by_name('Sheet3')

for row in ws.iter_rows():
    for cell in row:
        if 'C' in cell.coordinate:
            print cell.value

listaClientes =[]
    for row in datos.iter_rows(min_row=2, min_col=3, max_col=3):
        for cell in row:
            listaClientes.append(cell.value)

언급URL : https://stackoverflow.com/questions/38619471/iterate-through-all-rows-in-specific-column-openpyxl

반응형