[엑셀과 함께 춤을] 그렇다면 표는 ?

엑셀은 시트 말고 ‘표’ 기능도 있습니다.

혹시 이건 어떻게 되는지 테스트 해봅니다.

image


표 목록을 보여달라고 하니, 못합니다.

시트 목록을 보여주고 있습니다.

image


코드 인터프리터를 쓰지도 않았어요.

fetch_file({
  doc_name: "뭔가통합_전치_표.xlsx"
});

강제로 코드 인터 프리터를 쓰게 해봅니다.

image


이상합니다.

표를 보여달라고 하는데 시트 이름을 출력하는 코드를 짜서 수행합니다.

import pandas as pd

# 엑셀 파일 로드
excel_file = "뭔가통합_전치_표_공백제거.xlsx"
xls = pd.ExcelFile(excel_file)

# 시트 이름 목록 추출
sheet_names = xls.sheet_names
sheet_names

하도 이상해서 코파일럿 에게 물어봅니다. 그랬더니 openpyxl 라이브러리를 쓰라고 하네요.

맞습니다. 앞서의 테스트에서 간혹 나왔던 라이브러리 입니다. pandas 는 못하는 걸 얘는 할 수 있나 봅니다.

image


강제로 openpyxl 라이브러리를 쓰라고 해보겠습니다. 그래도 안되요…

image


그런데 코드를 보니 아직도 시트 네임을 찾는 코드를 짜고 있습니다.

from openpyxl import load_workbook

# Load the Excel workbook
workbook = load_workbook(filename="뭔가통합_전치_표_공백제거.xlsx")

# Get all sheet names
sheet_names = workbook.sheetnames
print("Sheet names:", sheet_names)

# Display the headers from each sheet
for sheet_name in sheet_names:
    sheet = workbook[sheet_name]
    headers = [cell.value for cell in next(sheet.iter_rows(min_row=1, max_row=1))]
    print(f"Headers in sheet '{sheet_name}': {headers}")

혹시나 ‘표’ 라는 한글이 ? 테이블로 말을 바꿔서 해봅니다.

엑셀 영문판에서는 저게 테이블 이거든요.

이제 됩니다. 표가 나옵니다.

image


코드가 딱 table 을 찾는 코드네요.

이건 표라고 하면 안되고 무조건 테이블 이라고 해야 겠습니다.

from openpyxl import load_workbook

# Load the workbook
workbook = load_workbook(filename="뭔가통합_전치_표_공백제거.xlsx")

# Collect all table names from all sheets
table_names = []
for sheet in workbook.worksheets:
    for table in sheet._tables.values():
        table_names.append(table.name)

# Display the table names
table_names

자 테이블에 접근이 되니 테이블 안에 있는 ‘한글 프롬프트’ 컬럼 값을 모아 보게 합니다.

갑자기 멍청한 짓을 합니다. 테이블 이름도 안맞고 값도 안 맞습니다.

image


코드를 보면 한글이 좀 깨집니다…. 아우… 진짜.. 이러니까 제대로 안나오지지

import pandas as pd

# Load the Excel file using openpyxl engine
excel_file = '뭔가통합_전치_표_공백제거.xlsx'
xls = pd.ExcelFile(excel_file, engine='openpyxl')

# Prepare a dictionary to store prompts from each table
prompt_summary = {}

# Iterate through each sheet and extract the Korean prompts
for sheet_name in xls.sheet_names:
    df = pd.read_excel(xls, sheet_name=sheet_name, engine='openpyxl')
    
    # Try to find a column that contains Korean prompts
    for col in df.columns:
        if df[col].dtype == object and df[col].astype(str).str.contains('[가-힣]').any():
            # Store non-empty Korean prompts from the column
            prompts = df[col].dropna().astype(str)
            korean_prompts = [p for p in prompts if any('\uac00' <= ch <= '\ud7a3' for ch in p)]
            prompt_summary[sheet_name] = korean_prompts
            break

# Convert the summary dictionary to a DataFrame for display
summary_df = pd.DataFrame([
    {'Table': table, 'Korean Prompt': prompt}
    for table, prompts in prompt_summary.items()
    for prompt in prompts
])

print(summary_df)

다시 한번 심기일전 해서 시켜봅니다. openpyxl 라이브러리도 명시해주고..

값은 나오는데… 시트 이름이 나오질 않나…

image


from openpyxl import load_workbook

# Load the workbook
wb = load_workbook('뭔가통합_전치_표_공백제거.xlsx')

# Dictionary to store sheet name and corresponding Korean prompts
prompt_summary = {}

# Iterate through each sheet in the workbook
for sheet_name in wb.sheetnames:
    sheet = wb[sheet_name]
    prompts = []

    # Iterate through rows and collect Korean prompt-like text
    for row in sheet.iter_rows(values_only=True):
        for cell in row:
            if isinstance(cell, str) and any('\uac00' <= ch <= '\ud7a3' for ch in cell):  # Check for Korean characters
                prompts.append(cell)

    # Store unique prompts for the sheet
    prompt_summary[sheet_name] = list(set(prompts))

# Display the summary table
for sheet, prompts in prompt_summary.items():
    print(f"Sheet: {sheet}")
    for prompt in prompts:
        print(f"  - {prompt}")
    print()

한번 더!!!

image


안되겠습니다..

테이블은 포기…..