108 lines
3.9 KiB
Python
108 lines
3.9 KiB
Python
from openpyxl import load_workbook
|
|
from config import ADDRESS_COLUMN, POSTAL_CODE_COLUMN
|
|
|
|
|
|
class ExcelHandler:
|
|
"""엑셀 파일에서 주소를 읽고 우편번호를 추가"""
|
|
|
|
def __init__(self, file_path):
|
|
"""
|
|
Args:
|
|
file_path (str): 엑셀 파일 경로
|
|
"""
|
|
self.file_path = file_path
|
|
self.workbook = None
|
|
self.worksheet = None
|
|
|
|
def open_file(self):
|
|
"""엑셀 파일을 엽니다"""
|
|
try:
|
|
self.workbook = load_workbook(self.file_path)
|
|
self.worksheet = self.workbook.active
|
|
print(f"✓ 파일 열기 성공: {self.file_path}")
|
|
return True
|
|
except FileNotFoundError:
|
|
print(f"✗ 파일을 찾을 수 없습니다: {self.file_path}")
|
|
return False
|
|
except Exception as e:
|
|
print(f"✗ 파일 열기 실패: {str(e)}")
|
|
return False
|
|
|
|
def get_column_index(self, column_name):
|
|
"""컬럼 이름으로부터 컬럼 인덱스를 찾습니다"""
|
|
for cell in self.worksheet[1]:
|
|
if cell.value == column_name:
|
|
return cell.column
|
|
return None
|
|
|
|
def get_addresses(self):
|
|
"""엑셀에서 주소 컬럼을 읽어서 주소 리스트를 반환합니다"""
|
|
address_col = self.get_column_index(ADDRESS_COLUMN)
|
|
|
|
if address_col is None:
|
|
print(f"✗ '{ADDRESS_COLUMN}' 컬럼을 찾을 수 없습니다")
|
|
return None
|
|
|
|
addresses = []
|
|
for row in range(2, self.worksheet.max_row + 1):
|
|
cell_value = self.worksheet.cell(row, address_col).value
|
|
if cell_value:
|
|
addresses.append(str(cell_value).strip())
|
|
|
|
print(f"✓ {len(addresses)}개의 주소를 읽었습니다")
|
|
return addresses
|
|
|
|
def add_postal_codes(self, postal_code_dict):
|
|
"""
|
|
우편번호 딕셔너리를 엑셀에 추가합니다.
|
|
|
|
Args:
|
|
postal_code_dict (dict): {주소: 우편번호} 형태의 딕셔너리
|
|
"""
|
|
# "우편번호" 컬럼이 없으면 추가
|
|
postal_col = self.get_column_index(POSTAL_CODE_COLUMN)
|
|
if postal_col is None:
|
|
postal_col = self.worksheet.max_column + 1
|
|
self.worksheet.cell(1, postal_col).value = POSTAL_CODE_COLUMN
|
|
print(f"✓ '{POSTAL_CODE_COLUMN}' 컬럼 추가됨 (컬럼 {postal_col})")
|
|
|
|
address_col = self.get_column_index(ADDRESS_COLUMN)
|
|
if address_col is None:
|
|
print(f"✗ '{ADDRESS_COLUMN}' 컬럼을 찾을 수 없습니다")
|
|
return False
|
|
|
|
# 주소와 매칭하여 우편번호 입력
|
|
updated_count = 0
|
|
for row in range(2, self.worksheet.max_row + 1):
|
|
address = self.worksheet.cell(row, address_col).value
|
|
if address:
|
|
address_str = str(address).strip()
|
|
if address_str in postal_code_dict:
|
|
postal_code = postal_code_dict[address_str]
|
|
self.worksheet.cell(row, postal_col).value = postal_code
|
|
updated_count += 1
|
|
|
|
print(f"✓ {updated_count}개 행의 우편번호가 추가되었습니다")
|
|
return True
|
|
|
|
def save_file(self, output_path=None):
|
|
"""
|
|
엑셀 파일을 저장합니다.
|
|
|
|
Args:
|
|
output_path (str): 저장할 파일 경로 (None이면 원본 파일 덮어쓰기)
|
|
"""
|
|
try:
|
|
save_path = output_path or self.file_path
|
|
self.workbook.save(save_path)
|
|
print(f"✓ 파일 저장 완료: {save_path}")
|
|
return True
|
|
except Exception as e:
|
|
print(f"✗ 파일 저장 실패: {str(e)}")
|
|
return False
|
|
|
|
def close_file(self):
|
|
"""파일을 닫습니다"""
|
|
if self.workbook:
|
|
self.workbook.close()
|