컴퓨터/Python

python xls 파일 병합셀 해제 최종

풍경소리^^ 2024. 11. 2. 17:23

xlsx → xls

import win32com.client as win32
import os

# def main(FILE_SOURCE,FILE_TARGET):
def main():
    # Excel 객체 생성
    excel_app = win32.gencache.EnsureDispatch('Excel.Application')
    
    # 현재 작업 디렉토리
    current_path = os.getcwd()
    
    # 파일 경로 생성
    file_source = os.path.join(current_path, FILE_SOURCE)
    file_target = os.path.join(current_path, FILE_TARGET)
    
    # 기존 .xlsx 파일이 존재하는 경우 삭제
    if os.path.exists(file_target):
        os.remove(file_target)
    
    # .xls 파일 열기
    # wb = excel_app.Workbooks.Open("B:\python\jupyternotebook\pandas_엑셀투파이썬\mergecell1.xls")
    wb = excel_app.Workbooks.Open(file_source)
    
    # .xlsx 파일로 저장하기
    # wb.SaveAs(file_path2, FileFormat=51) # xls 확장자를 xlsx 확장자로 바꾸기
    wb.SaveAs(file_target, FileFormat=56) # xlsx 확장자를 xls 확장자로 바꾸기
    
    # 파일 닫기
    wb.Close()
    
    # Excel 종료
    excel_app.Application.Quit()
if __name__ == '__main__':
    file_source = "03countifsumif.xlsx"
    file_target = "03countifsumif.xls"
    main()

 

병합 셀 해제

import win32com.client as win32
import os
from openpyxl import load_workbook


# 병합된 셀 찾기 및 해제 함수
def find_and_unmerge_merged_cells(file_path, original_file):
    workbook = load_workbook(file_path)
    sheet = workbook.active  # 첫 번째 시트 선택

    merged_cells = [str(range_ref) for range_ref in sheet.merged_cells.ranges]
    if merged_cells:
        fn_unmerge_cells(sheet)
        workbook.save(file_path)  # 수정된 내용을 파일에 저장

        # 기존 .xls 파일 삭제 후 .xlsx를 다시 .xls로 변환
        if os.path.exists(original_file):
            os.remove(original_file)

        excel_app = win32.gencache.EnsureDispatch('Excel.Application')
        excel_app.Visible = False  # 백그라운드 실행
        wb = excel_app.Workbooks.Open(file_path)
        wb.SaveAs(original_file, FileFormat=56)  # 56: .xls 파일 형식
        wb.Close()
        excel_app.Application.Quit()
        excel_app = None  # Excel 프로세스 종료
    else:
        print("병합된 셀이 없습니다.")
    return merged_cells

# 병합된 셀 해제 함수
def fn_unmerge_cells(sheet):
    # 병합된 셀 해제
    merged_cells = list(sheet.merged_cells.ranges)
    for merged_range in merged_cells:
        sheet.unmerge_cells(str(merged_range))

# main 함수 정의
def main():
    excel_app = win32.gencache.EnsureDispatch('Excel.Application')
    current_path = os.getcwd()
    file_source = os.path.join(current_path, FILE)
    file_temp = os.path.join(current_path, "temp.xlsx")

    # 기존 .xlsx 파일이 존재하는 경우 삭제
    if os.path.exists(file_temp):
        os.remove(file_temp)

    # .xls 파일 열기 및 .xlsx 파일로 저장하기
    wb = excel_app.Workbooks.Open(file_source)
    wb.SaveAs(file_temp, FileFormat=51)  # 51: .xlsx 파일 형식
    wb.Close()
    excel_app.Application.Quit()
    excel_app = None  # Excel 프로세스 종료

    # 병합된 셀 찾기 및 해제 수행
    # merged_cells = find_and_unmerge_merged_cells(file_temp, file_source)
    # print("병합된 셀 위치 리스트:", merged_cells)
    find_and_unmerge_merged_cells(file_temp, file_source)

# main 함수 호출
if __name__ == "__main__":
    FILE = "03countifsumif.xls"
    main()