ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • drawio 파일을 python 코드를 활용해 엑셀 데이터로 변환하는 방법
    Python 2025. 2. 14. 11:34
    반응형

    Drawio에서 ERD용도로 사용하던 drawio파일을 python 코드를 활용해 엑셀 데이터로 변환하는 방법

    import xml.etree.ElementTree as ET
    import pandas as pd
    import re
    
    def clean_text(text):
        """ 불필요한 HTML 태그 및 특정 문자열 제거 """
        text = re.sub(r'<.*?>', '', text)  # 모든 HTML 태그 제거
        text = re.sub(r'p style="[^"]*"', '', text)  # <p style="margin, "> 같은 스타일 태그 제거
        text = re.sub(r'<p style="margin', '', text)  # "<p style="margin, " 제거
        text = text.replace("&lt;", "").replace("&gt;", "").strip()  # 특수문자 변환
        return text
    
    def remove_leading_comma_space(text):
        """ 첫 번째 ', ' 만 제거 (B열 데이터 전용) """
        return text.lstrip(", ")  # 문자열 왼쪽(Lstrip)에서 ", " 제거
    
    def extract_table_data(drawio_file):
        """ draw.io 파일에서 테이블 이름과 컬럼명 추출 """
        tree = ET.parse(drawio_file)
        root = tree.getroot()
    
        tables = []
    
        # XML의 모든 mxCell 요소 확인
        for cell in root.findall(".//mxCell"):
            value = cell.get("value")
    
            if value and "<b>" in value:  # 테이블 이름 감지
                table_name = clean_text(value.split("<b>")[1].split("</b>")[0])
                raw_columns = value.split("<br/>")
    
                # 컬럼 추출 (불필요한 태그, 스타일 정보 제거)
                columns = [clean_text(col.split(":")[0].strip()) for col in raw_columns if ":" in col]
    
                # 컬럼 리스트를 문자열로 변환 후, 처음 등장하는 ', ' 제거
                columns_str = ", ".join(columns)
                columns_str = remove_leading_comma_space(columns_str)  # 최종적으로 첫 번째 ", " 제거
    
                tables.append({"Table Name": table_name, "Columns": columns_str})
    
        return tables
    
    def save_to_excel(tables, output_file="output.xlsx"):
        """ 추출한 데이터를 Excel로 저장 (B열에서 ', ' 완전히 제거) """
        df = pd.DataFrame(tables)
        
        # 엑셀 저장 전, B열 데이터에서 남아있는 ", " 제거
        df["Columns"] = df["Columns"].apply(remove_leading_comma_space)
    
        df.to_excel(output_file, index=False)
        print(f"Excel 파일 저장 완료: {output_file}")
    
    # 실행
    drawio_file = "input.drawio"  # 변환할 draw.io 파일
    tables = extract_table_data(drawio_file)
    save_to_excel(tables)
    반응형

    댓글

Designed by Tistory.