반응형
def add_columns_if_missing(file_path, column_names):
# 엑셀 파일 열기
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active
# 헤더로 사용될 첫 번째 행에서 모든 컬럼 이름 가져오기
headers = [cell.value for cell in sheet[1]] # 1행의 모든 셀 값을 리스트로 저장
# 현재 헤더에 몇 개의 컬럼이 있는지 확인
current_max_column = len(headers)
print("current_max_column", current_max_column)
# 주어진 컬럼 이름들 중 누락된 것이 있는지 확인하고 추가
for column_name in column_names:
if column_name not in headers:
# 새 컬럼 위치 결정
current_max_column += 1
# 새 컬럼 추가
sheet.cell(row=1, column=current_max_column, value=column_name)
# 변경된 내용을 동일 파일에 저장
workbook.save(file_path)
사용예시
기존에 있던 파일에서 새로운 파일로 생성 후 오른쪽에 필요한 컬럼들을 새로 추가한다.
def copy_file(file_path):
file_name = Path(file_path).stem
now = datetime.now()
str_now = now.strftime("%Y%m%d%H%M%S")
config = ProgramConfig()
destination_path = os.path.join(config.today_output_folder, f"{file_name}_{str_now}.xlsx")
shutil.copy(file_path, destination_path)
return destination_path
new_columns = [
"부동산식별번호",
"기본정보",
"소유주1",
"소유주2",
"소유주3",
"공주가",
"대지권",
"디스코_대지면적",
"디스코_건축면적",
"디스코_건폐율",
"디스코_연면적",
"디스코_용적률산정연면적",
"디스코_용적률",
"디스코_외필지수",
"디스코_국토계획",
"디스코_기타법률",
"디스코_용도지역",
"디스코_토지면적",
]
result_file = copy_file(input_excel)
self.add_columns_if_missing(result_file, new_columns)
반응형
'프로그래밍 > python' 카테고리의 다른 글
| 두 엑셀파일을 비교하여, 다른 데이터가 있는 경우 색깔로 표시해주는 파이썬 코드 (0) | 2024.05.09 |
|---|---|
| python pyinstaller로 만든 exe 파일을 inno setup 6 버전으로 만들기(한글 설치) (0) | 2024.04.19 |
| python 코드로 pnu(필지고유번호) 번호 만드는 방법 (0) | 2024.04.09 |
| [FastAPI] 307 Temporary Redirect 오류 나는 원인 (0) | 2024.02.16 |
| Pyqt5, PySide6 년도 선택 위젯 만들기 (1) | 2024.02.08 |