MoonNote

반응형
     

 

 

 

엑셀 실습 파일

Find Cell Value Example File.xlsx
0.01MB
Replaced Cell Value Example File.xlsx
0.01MB

 

엑셀 파일 구성

예제 코드 01 실행 전 : 셀 값 검색 '!' → 개수 및 위치 정보 출력

 Find Cell Value Example File.xlsx

예제 코드 01 파일 정보

예제 코드 02 실행 후 : 셀 값 '!' → '@' 변경 

Replaced Cell Value Example File.xlsx

예제 코드 02 파일 정보

 

셀 값 검색 예제 코드 01

지정한 엑셀 파일의 시트에서 특정 셀 값(!) 검색

검색하는 값이 있을 경우, 일치하는 값의 개수 카운팅 및 Cell 좌표 출력

from openpyxl import load_workbook

def search_cell_value(workbook_path, sheet_name, target_value):
    # Load an excel file
    wb = load_workbook(filename=workbook_path)
    
    # select the sheet
    sheet = wb[sheet_name]

    # Initialize dictionary to store results
    result = {'value': target_value, 'count': 0, 'positions': []}

    # Search for all cells in the sheet
    for row in range(1, sheet.max_row + 1):
        for column in range(1, sheet.max_column + 1):
            cell = sheet.cell(row=row, column=column)
            # Verify that the value of the cell matches the target value
            if cell.value == target_value:
                # In case of matching value, records searched count and position information
                result['count'] += 1
                result['positions'].append((row, column))

    return result

# You must change the physical path before running this script.
currPath = "C:/Users/natio/OneDrive/0. Personal Blog/05. Python/05. OPENPYXL/02. Cell Example/"
workbook_path = currPath+"Find Cell Value Example File.xlsx"
# input sheet name and searching string
sheet_name = 'Sample Sheet'
target_value = '!'

result = search_cell_value(workbook_path, sheet_name, target_value)

print(f"검색한 값: {result['value']}")
print(f"총 개수: {result['count']}")
print("위치 정보:")
for position in result['positions']:
    print(f"행: {position[0]}, 열: {position[1]}")

 

결과 값

검색한 값: !
총 개수: 4
위치 정보:
행: 5, 열: 1
행: 10, 열: 1
행: 15, 열: 1
행: 20, 열: 1

 

셀 값 검색 및 대체 예제 코드 02

 지정한 엑셀 파일의 시트에서 특정 셀 값(!) 검색

모든 셀을 검색하면서 값이 일치할 경우 지정한 값(@)로 변경

검색하는 값이 있을 경우, 일치하는 값의 개수 카운팅 및 Cell 좌표 출력

from openpyxl import load_workbook

def search_cell_value(workbook_path, sheet_name, target_value):
    # Load an excel file
    wb = load_workbook(filename=workbook_path)
    
    # select the sheet
    sheet = wb[sheet_name]

    # Initialize dictionary to store results
    result = {'value': target_value, 'count': 0, 'positions': []}

    # Search for all cells in the sheet
    for row in range(1, sheet.max_row + 1):
        for column in range(1, sheet.max_column + 1):
            cell = sheet.cell(row=row, column=column)
            # Verify that the value of the cell matches the target value
            if cell.value == target_value:
                # In case of matching value, records searched count and position information
                result['count'] += 1
                result['positions'].append((row, column))

    return result

def replace_cell_value(workbook_path, sheet_name, target_value, replacement, new_workbook_path):
    # Load an excel file
    wb = load_workbook(filename=workbook_path)
    
    # select the sheet
    sheet = wb[sheet_name]

    # Search for all cells in the sheet
    for row in range(1, sheet.max_row + 1):
        for column in range(1, sheet.max_column + 1):
            cell = sheet.cell(row=row, column=column)
            # Verify that the value of the cell matches the target value
            if cell.value == target_value:
                # Replace if value is matched
                cell.value = replacement

    # Save changes
    wb.save(new_workbook_path)


# You must change the physical path before running this script.
currPath = "C:/Users/natio/OneDrive/0. Personal Blog/05. Python/05. OPENPYXL/02. Cell Example/"
workbook_path = currPath+"Find Cell Value Example File.xlsx"

# Set input values
sheet_name = 'Sample Sheet'
target_value = '!'
replacement = '@'
new_workbook_path = currPath+"Replaced Cell Value Example File.xlsx"

# Replace searching value
replace_cell_value(workbook_path, sheet_name, target_value, replacement, new_workbook_path)
# Result
result = search_cell_value(workbook_path, sheet_name, target_value)

print(f"검색 문자 : {result['value']}, 대체 문자 : {replacement}")
print(f"총 개수: {result['count']}")
print("위치 정보:")
for position in result['positions']:
    print(f"행: {position[0]}, 열: {position[1]}")

 결과 값

검색 문자 : !, 대체 문자 : @
총 개수: 4
위치 정보:
행: 5, 열: 1
행: 10, 열: 1
행: 15, 열: 1
행: 20, 열: 1

 

 

 

 

 

 

 

 

 

 

※ 이 글이 도움이 되었다면 "👆🏻구독"과 "🤍공감" 버튼을 클릭해주세요. 클릭 한번이 글 쓰는데 큰 힘이 됩니다.

공유하기

facebook twitter kakaoTalk kakaostory naver band