프로그램/Python Project

[Python Project] (코드) 엑셀JSON변환 -XSL2JSON-

리덕토 2025. 5. 13. 15:26

- 프로그램명 : XLS2JSON.py
- 제작기간 : '25. 5. 6.(1일)
- 제작자 : REDUCTO
- 사용언어 : Python
- 사용라이브러리 : pandas, tqdm

- 버전 : v1.0


소개

기술사공부를 하다가 평소 gemini AI와의 대화(Live)로 연습을 하는데 얘한테 input source로 제가 공부하고 있는 파일을 주고 싶어서 만들어 보았습니다. exe로 만들까 하다가 cli기반이고, 파라미터들로 직접조정하는게 좋을거 같다는 것과, 어짜피 python을 기반으로 exe를 만들면 너무 느려지기 때문에, 코드로만 배포합니다. 하단에 사용법에 코드 실행방법까지 자세하게 표기하겠습니다.
 

* 무단배포는 금지합니다.(댓글달아주세용)
* 기능에 커스터마이징이 필요하시다면 댓글달아주세용


사용법

# ==============================================================================
# XLS2JSON: Excel to JSON Converter
# ==============================================================================
#
# 설명:
#   이 스크립트는 Excel 파일(.xlsx, .xls)을 읽어 JSON 형식으로 변환하는
#   명령줄 인터페이스(CLI) 도구입니다. 데이터 시작 위치를 자동으로 감지하며,
#   특정 시트 또는 모든 시트를 변환하고, 결과를 콘솔 또는 파일로 출력할 수 있습니다.
#   여러 시트를 처리할 때 진행률 표시줄을 보여줍니다.
#
# 필요한 라이브러리 설치:
#   pip install pandas openpyxl tqdm
#
# 기본 사용법:
#   python xls2json.py <입력_Excel_파일경로> [옵션]
#
# 옵션:
#   <입력_Excel_파일경로> : 변환할 Excel 파일의 경로 (필수)
#
#   -o, --output <출력_파일경로> :
#       변환된 JSON 결과를 저장할 파일 경로입니다.
#       지정하지 않으면 결과가 콘솔(표준 출력)에 표시됩니다.
#       예: -o result.json
#
#   -s, --sheet <시트_이름_또는_인덱스> :
#       변환할 특정 시트의 이름(문자열) 또는 0부터 시작하는 인덱스(숫자)입니다.
#       기본값은 0 (첫 번째 시트)입니다.
#       --all-sheets 옵션이 사용되면 이 옵션은 무시됩니다.
#       예: -s "데이터 시트"
#       예: -s 1  (두 번째 시트를 의미)
#
#   -a, --all-sheets :
#       Excel 파일 내의 모든 시트를 변환합니다.
#       이 옵션을 사용하면 결과 JSON은 각 시트 이름을 키로 가지는 객체 형태가 됩니다.
#       예: {"Sheet1": [...], "Sheet2": [...]}
#
# 실행 예시:
#   # 1. 첫 번째 시트를 콘솔에 출력
#   python xls2json.py data.xlsx
#
#   # 2. '매출데이터' 시트를 result.json 파일로 저장
#   python xls2json.py data.xlsx -s "매출데이터" -o result.json
#
#   # 3. 두 번째 시트(인덱스 1)를 console_output.json 파일로 저장
#   python xls2json.py data.xlsx -s 1 -o console_output.json
#
#   # 4. 모든 시트를 all_sheets.json 파일로 저장 (시트 이름별로 구분됨)
#   python xls2json.py data.xlsx -a -o all_sheets.json
#
# ==============================================================================

import pandas as pd
import argparse
import sys
import json
import os
from tqdm import tqdm

# --- 이하 코드는 이전과 동일 ---

def find_and_process_data(df):
    """
    데이터프레임에서 데이터 시작 위치를 찾아 처리하고,
    첫 행을 헤더로 사용하여 Python 객체 리스트로 변환합니다.
    """
    df_processed = df.dropna(how='all').dropna(how='all', axis=1)
    if df_processed.empty:
        return []
    new_header = df_processed.iloc[0].astype(str)
    df_processed = df_processed[1:]
    df_processed.columns = new_header
    df_processed = df_processed.reset_index(drop=True)
    df_processed = df_processed.where(pd.notnull(df_processed), None)
    return df_processed.to_dict(orient='records')

def convert_single_sheet_to_json(file_path, sheet_name=0):
    """
    Excel 파일의 지정된 단일 시트를 읽어 자동 감지 후 JSON 문자열로 변환합니다.
    """
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name, header=None, engine='openpyxl')
        processed_data = find_and_process_data(df)
        json_data = json.dumps(processed_data, indent=4, ensure_ascii=False)
        return json_data
    except FileNotFoundError:
        print(f"오류: 파일을 찾을 수 없습니다 - {file_path}", file=sys.stderr)
        return None
    except ValueError as ve:
        print(f"오류: 시트 '{sheet_name}' 처리 중 오류 발생. 시트 이름/인덱스를 확인하세요. 에러: {ve}", file=sys.stderr)
        return None
    except Exception as e:
        print(f"오류: 단일 시트 처리 중 예외 발생 ({type(e).__name__}) - {e}", file=sys.stderr)
        return None


def convert_all_sheets_to_json(file_path):
    """
    Excel 파일의 모든 시트를 읽어 자동 감지 후 시트 이름을 키로 하는 JSON 객체 문자열로 변환합니다.
    """
    try:
        all_sheets_df_map = pd.read_excel(file_path, sheet_name=None, header=None, engine='openpyxl')

        all_sheets_data = {}
        print("시트 처리 중...", file=sys.stderr)
        for sheet_name, df in tqdm(all_sheets_df_map.items(), desc="Processing sheets", unit="sheet", leave=False):
            try:
                processed_data = find_and_process_data(df)
                all_sheets_data[sheet_name] = processed_data
            except Exception as e:
                print(f"\n경고: 시트 '{sheet_name}' 처리 중 오류 발생하여 건너뜁니다 ({type(e).__name__}) - {e}", file=sys.stderr)
                all_sheets_data[sheet_name] = {"error": f"Failed to process sheet: {e}"}

        json_data = json.dumps(all_sheets_data, indent=4, ensure_ascii=False)
        return json_data

    except FileNotFoundError:
        print(f"오류: 파일을 찾을 수 없습니다 - {file_path}", file=sys.stderr)
        return None
    except Exception as e:
        print(f"오류: 모든 시트 처리 중 예외 발생 ({type(e).__name__}) - {e}", file=sys.stderr)
        return None

def save_to_file(data, output_file):
    """
    주어진 데이터를 지정된 파일 경로에 UTF-8 인코딩으로 저장합니다.
    """
    try:
        output_dir = os.path.dirname(output_file)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(data)
        return True
    except IOError as e:
        print(f"오류: 파일 '{output_file}'에 쓰는 중 오류 발생 - {e}", file=sys.stderr)
        return False
    except Exception as e:
        print(f"오류: 파일 저장 중 예기치 않은 오류 발생 ({type(e).__name__}) - {e}", file=sys.stderr)
        return False

def main():
    parser = argparse.ArgumentParser(
        description="XLS2JSON: Excel to JSON Converter with auto-detection and progress bar.",
        epilog="Example: python xls2json.py data.xlsx -a -o output.json" # 에필로그 추가
    )
    parser.add_argument("excel_file", help="Path to the input Excel file.")
    parser.add_argument(
        "-s", "--sheet",
        default=0,
        help="Specify sheet name or 0-based index to convert (default: 0). Ignored if --all-sheets is used."
    )
    parser.add_argument(
        "-a", "--all-sheets",
        action='store_true',
        help="Convert all sheets in the Excel file. Output JSON will be an object with sheet names as keys."
    )
    parser.add_argument(
        "-o", "--output",
        help="Path to the output JSON file. If not specified, output will be printed to the console."
    )

    args = parser.parse_args()

    json_output = None
    action_description = ""

    if args.all_sheets:
        action_description = "Convert all sheets with auto-detection"
        json_output = convert_all_sheets_to_json(args.excel_file)
    else:
        sheet_identifier = args.sheet
        try:
            sheet_identifier_int = int(args.sheet)
            sheet_identifier = sheet_identifier_int
        except ValueError:
            pass
        action_description = f"Convert sheet '{sheet_identifier}' with auto-detection"
        print(f"Processing: {action_description}...", file=sys.stderr)
        json_output = convert_single_sheet_to_json(args.excel_file, sheet_name=sheet_identifier)

    if json_output:
        if args.output:
            print(f"Saving results to '{args.output}'...", file=sys.stderr)
            if save_to_file(json_output, args.output):
                 print(f"Success: {action_description} completed. Results saved to '{args.output}'.", file=sys.stderr)
            else:
                sys.exit(1)
        else:
            print(json_output) # Print JSON to stdout
    else:
        print(f"Error: Failed during '{action_description}'.", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()

 

* 사전준비

 - python이 설치되어있어야합니다.

 - 필자의 환경은 python 3.13.0입니다. 가급적 맞추어주시거나 상위버전을 사용해 주시는게 좋습니다.

 

1. 해당 파일을 xls2json.py로 저장합니다.

2. 아래 requiremets.txt를 다운로드 받습니다.

requirements.txt
0.00MB

 

3. cmd를 켜고(Python 경로 Path에 포함되어있어야합니다) 다음과 같이 입력합니다(requirements.txt가 있는 경로에서)

pip install -r requirements.txt

 

4. 코드 상단에 사용방법과 같이 XLS2JSON을 사용해 주시면 됩니다. 

# ==============================================================================
# XLS2JSON: Excel to JSON Converter
# ==============================================================================
#
# 설명:
#   이 스크립트는 Excel 파일(.xlsx, .xls)을 읽어 JSON 형식으로 변환하는
#   명령줄 인터페이스(CLI) 도구입니다. 데이터 시작 위치를 자동으로 감지하며,
#   특정 시트 또는 모든 시트를 변환하고, 결과를 콘솔 또는 파일로 출력할 수 있습니다.
#   여러 시트를 처리할 때 진행률 표시줄을 보여줍니다.
#
# 필요한 라이브러리 설치:
#   pip install pandas openpyxl tqdm
#
# 기본 사용법:
#   python xls2json.py <입력_Excel_파일경로> [옵션]
#
# 옵션:
#   <입력_Excel_파일경로> : 변환할 Excel 파일의 경로 (필수)
#
#   -o, --output <출력_파일경로> :
#       변환된 JSON 결과를 저장할 파일 경로입니다.
#       지정하지 않으면 결과가 콘솔(표준 출력)에 표시됩니다.
#       예: -o result.json
#
#   -s, --sheet <시트_이름_또는_인덱스> :
#       변환할 특정 시트의 이름(문자열) 또는 0부터 시작하는 인덱스(숫자)입니다.
#       기본값은 0 (첫 번째 시트)입니다.
#       --all-sheets 옵션이 사용되면 이 옵션은 무시됩니다.
#       예: -s "데이터 시트"
#       예: -s 1  (두 번째 시트를 의미)
#
#   -a, --all-sheets :
#       Excel 파일 내의 모든 시트를 변환합니다.
#       이 옵션을 사용하면 결과 JSON은 각 시트 이름을 키로 가지는 객체 형태가 됩니다.
#       예: {"Sheet1": [...], "Sheet2": [...]}
#
# 실행 예시:
#   # 1. 첫 번째 시트를 콘솔에 출력
#   python xls2json.py data.xlsx
#
#   # 2. '매출데이터' 시트를 result.json 파일로 저장
#   python xls2json.py data.xlsx -s "매출데이터" -o result.json
#
#   # 3. 두 번째 시트(인덱스 1)를 console_output.json 파일로 저장
#   python xls2json.py data.xlsx -s 1 -o console_output.json
#
#   # 4. 모든 시트를 all_sheets.json 파일로 저장 (시트 이름별로 구분됨)
#   python xls2json.py data.xlsx -a -o all_sheets.json
#
# ==============================================================================

 

EASY합니다 끝t