Python을 사용한 Excel 자동화 : 위도 및 경도

12641 단어 excelpythonautomation
며칠 전 고객으로부터 지질 데이터가 포함된 엑셀 파일을 받았습니다. 파일에는 다음과 같은 사이트 ID, 위도 및 경도가 포함되어 있습니다.



내 고객의 목표는 다음과 같습니다.
  • 빈 셀을 강조 표시합니다.
  • 경도와 위도를 소수점 이하 6자리로 통일하고 오류를 수정하거나 강조 표시합니다.

  • 데모 파일을 보면 간단한 작업처럼 보일 수 있지만 실제 파일에는 10,000줄 이상의 데이터가 포함되어 있고 클라이언트가 최대한 빨리 완료하기를 원하므로 Python을 사용하여 내 방식대로 수행해야 합니다.



    설정



    나는 openpyxl보다 xlwings을 선택합니다. 둘 다 엑셀 파일을 읽고 쓸 수 있는 훌륭한 파이썬 라이브러리입니다. 그러나 내 경험상 openpyxl은 대규모 데이터 세트를 처리할 때 더 빠르고 Excel 프로그램에 의존하지 않습니다.

    (참고: xlwings는 대화형 프로그램 작성과 같이 적절한 상황에서 사용될 때 빛을 발합니다.

    먼저 openpyxl을 설치합시다.

    pip install openpyxl
    


    이것은 매우 간단한 프로그램이므로 기본 루프에는 geo.py, 데이터 유효성 검사 및 Excel 편집에는 reviewer.py, 기본 루프에는 reviewer.py, 데이터 유효성 검사 및 Excel 편집에는 reviewer.py가 필요합니다.

    Python으로 데이터 읽기(geo.py)



    먼저 파일의 내용을 읽어야 합니다. geo.py를 열고 다음 코드를 작성합니다.

    from openpyxl import load_workbook, workbook
    from reviewer import reviewer_geo
    
    input_file_path = 'Geo Demo.xlsx'
    workbook = load_workbook(input_file_path)
    worksheet = workbook['Sheet1']
    
    col_latitude = 'B'
    col_longitude = 'C'
    


    Geo Demo.xlsx에서 로드됩니다Sheet1. worksheet = workbook[workbook.sheetnames[0]]를 사용하여 Geo Demo.xlsx에서 첫 번째 시트를 로드할 수도 있습니다. 이는 사용자가 기본 시트 이름을 변경할 수 있기 때문에 매우 유용합니다.

    또한 각 열에 해당하는 데이터를 선언합니다. 이렇게 하면 코드를 더 쉽게 읽을 수 있습니다. 또한 다른 열에 있을 수 있는 다른 파일의 지질학적 데이터를 검토해야 하는 경우 해당 선언만 변경하면 됩니다.

    다음으로 행을 반복하고 셀을 선택하고 review_geo 함수로 검토하고 마지막으로 검토된 데이터가 포함된 새 Excel 파일을 저장해 보겠습니다. geo.py에 다음 줄을 추가합니다.

    row_start = 2    # geo data starts at row 2
    row_end = 10    # geo data ends at row 10
    
    for i in range(row_start, row_end+1):
        cell_site = worksheet[f'{col_site}{i}']
        cell_latitude = worksheet[f'{col_latitude}{i}']
        cell_longitude = worksheet[f'{col_longitude}{i}']
    
        reviewer_geo(cell_latitude)
        reviewer_geo(cell_longitude)
    
    # save the updated excel
    output_file_path = 'Geo Demo Reviewed.xlsx'
    workbook.save(output_file_path)
    


    여기서는 rich을 사용하여 메인 루프에서 파일의 내용을 인쇄합니다(프로그램에 중요하지 않으므로 여기에 코드를 표시하지 않았습니다).



    데이터를 검토하자! (리뷰어.py)



    엑셀 파일에서 데이터를 검색한 후 검토 기능 작성을 시작할 수 있습니다.

    (참고: openpyxl에는 유효성 검사 기능이 내장되어 있지만 저는 보통 고객의 요구에 맞게 자체 유효성 검사기를 작성합니다.)

    엑셀에 댓글 쓰기



    먼저 openpyxl의 Comments 클래스를 사용하여 잘못된 지리 데이터가 포함된 셀에 주석을 추가합니다. 또한 openpyxl의 PatternFill 클래스를 사용하여 오류 셀을 배경으로 채우므로 사용자가 오류를 더 쉽게 식별할 수 있습니다.

    reviewer.py에서 두 개의 함수를 생성합니다. write_comment 셀에 빨간색 배경과 주석을 추가할 수 있습니다. add_green_bg 셀에 녹색 배경을 추가하기만 하면 됩니다.

    from openpyxl.comments import Comment
    from openpyxl.styles import PatternFill
    
    def write_comment(cell, comment_text):
        red_bg = PatternFill(fill_type='solid',
                             start_color='FF0000',
                             end_color='FF0000')
        cell.fill = red_bg
        comment = Comment(comment_text, 'Python')
        cell.comment = comment
    
    def add_green_bg(cell):
        green_bg = PatternFill(fill_type='solid',
                             start_color='00FF00',
                             end_color='00FF00')
        cell.fill = green_bg
    


    reviewer.py에서 reviewer_geo 함수를 생성합니다. 이 함수는 원하지 않는 값을 식별한 다음 주석을 작성하거나 포함하는 셀에 배경을 추가합니다. 다음 코드의 주석을 읽고 어떻게 작동하는지 확인할 수 있습니다.

    def reviewer_geo(cell):
        val_geo = cell.value
        str_geo = str(val_geo)
    
        # check if cell is empty
        if val_geo is None:
            write_comment('This cell must be filled')
    
        # if cell is not empty, check if cell contains float
        elif isinstance(val_geo, int):
            write_comment('This cell must be a float number')
    
        else:
            # if cell is not empty, but contains characters other than ditits and dicimal point
    
            for c in str_geo:
                if not c.isdigit() and c != '.':
                    write_comment('This cell must be a float number')
                    return
    
            # if cell value is a float number, check if cell contains float with 6 decimal places
            len_geo = len(str_geo.split('.')[-1])
            if len_geo != 6:
                if len_geo > 6:
                    cell.value = "{:.6f}".format(float(str_geo))    # remove extra decimal points
                else:
                    write_comment('Geo data must be a float number with 6 decimal places')
                    return
    


    결과



    geo.py를 실행하면 Geo Demo Reviewed.xlxs에서 원하는 결과를 얻을 수 있습니다. 내 경험으로는 10,000줄의 데이터로 몇 초 안에 완료할 수 있습니다!

    좋은 웹페이지 즐겨찾기