정제된 엑셀 매출 데이터를 바탕으로 파이썬 Streamlit과 배치파일(.bat)을 활용해 더블클릭 한 번으로 웹 브라우저에서 기간·지점별 필터링과 차트 시각화가 가능한 인터랙티브 대시보드 구축 방법과 전체 코드를 제공합니다.
매주 금요일 오후나 월말만 되면 등골이 서늘해지는 순간이 있습니다. 각 팀이나 지점에서 취합용 엑셀 파일이 하나둘 메일함으로 날아올 때죠. 파일 열어서 양식 안 맞는 셀 맞추고, '복사-붙여넣기' 무한 반복하다가 수식 깨지면 한숨부터 푹푹 쉬어지더라고요. 게다가 숫자가 수천 줄을 넘어가면 엑셀 창이 하얗게 굳어버리면서 '응답 없음'이 뜹니다. 그러다 보면 정작 중요한 분석은 시작도 못 했는데 벌써 배달 앱으로 야식 메뉴를 고르고 있는 제 자신을 발견하곤 했죠.
코딩 문법이라곤 1도 모르는 평범한 직장인이지만, 언제까지 이 단순 노동에 내 금쪽같은 저녁 시간을 바칠 수는 없잖아요? 그래서 저는 대화형 AI를 부사수 삼아 "여러 엑셀 파일 싹 합치고, 빈칸이나 오류 데이터 알아서 걸러낸 다음, 클릭 몇 번으로 필터링되는 인터랙티브 웹 대시보드"를 뚝딱 만들어버렸습니다. 제가 직접 검증해 본 가장 현실적이고 비용 안 드는 세팅법을 나눠볼게요.

엑셀 노가다 3단계, 한 번에 끝내는 AI 전략
우리가 보통 주간·월간 보고서를 만들 때 거치는 고통의 코스는 대략 세 단계입니다.
- 1단계: 파일 합치기 — 지점별, 기간별로 따로 저장된 수십 개의 엑셀 시트를 하나로 엮는 일.
- 2단계: 데이터 정제 — 날짜 형식이 제각각이거나(2026-05-01, 26.5.1 혼용), 빈칸(결측치)이나 오타 때문에 수식이 꼬이는 걸 일일이 손보는 일.
- 3단계: 시각화 및 보고서화 — 기껏 합친 데이터를 피벗 테이블 돌리고 차트 그려서 상사에게 보고 가능한 형태로 다듬는 일.
이 과정을 사람이 손으로 하면 꼬박 서너 시간이 걸리지만, 무료 파이썬 라이브러리(Pandas와 Streamlit)를 챗GPT나 제미나이에게 시키면 클릭 딱 한 번에 10초 만에 끝납니다. 우리가 코딩을 배울 필요는 전혀 없어요. 그냥 폴더 구조와 원하는 결과만 일상어로 명령하면 되니까요.
AI에게 복사해서 바로 쓰는 '원클릭 대시보드' 프롬프트
복잡하게 생각할 것 없이, AI에게 아래 프롬프트를 복사해서 여러분의 상황에 맞게 괄호 안의 내용만 살짝 바꿔 던져보세요. 파이썬이 깔려있지 않더라도 실행할 수 있는 가장 쉬운 방법까지 친절하게 알려줍니다.
너는 데이터 자동화 전문 파이썬 개발자야.
비전공자인 내가 클릭 한 번으로 실행할 수 있는 자동화 파이썬 코드를 작성해 줘.
[상황 및 요구사항]
1. 특정 폴더('data_input') 안에 들어있는 동일한 양식의 여러 개 엑셀(.xlsx, .csv) 파일을 하나로 합쳐줘.
2. 데이터 정제:
- '주문일자' 열은 무조건 'YYYY-MM-DD' 날짜 형태로 통일할 것.
- '매출액' 열에서 문자가 섞여 있거나 빈칸인 행은 0으로 채우고 숫자로 변환할 것.
- 중복된 주문번호는 최신 데이터 1개만 남기고 제거할 것.
3. 시각화(대시보드):
- 파이썬 'Streamlit' 라이브러리를 써서 브라우저에서 열리는 인터랙티브 대시보드로 만들어줘.
- 왼쪽 사이드바에서 '지점명'과 '기간'을 마우스 클릭으로 다중 선택(필터)할 수 있게 해줘.
- 화면 상단에는 총 매출액, 주문 건수 등의 주요 지표(KPI 카드)를 띄워줘.
- 하단에는 월별 매출 추이 꺾은선 그래프와 지점별 점유율 원형 차트를 반응형으로 보여줘.
4. 코딩을 모르는 내가 이 코드를 더블 클릭 한 번으로 실행할 수 있는 배치 파일(.bat) 만드는 법까지 순서대로 알려줘.
이렇게 명령을 넣으면 AI가 알아서 깔끔한 파이썬 스크립트 한 장과 실행 방법을 출력해 줍니다. 처음에는 "이게 진짜 웹페이지처럼 열린다고?" 싶었는데, 터미널에 명령어 한 줄 치자마자 로컬 브라우저에 알록달록한 반응형 대시보드가 뜨는 걸 보고 소름이 돋더라고요.
| 주문번호 | 주문일자 | 지점명 | 담당자 | 카테고리 | 상품명 | 수량 | 단가 | 매출액 |
|---|
데이터 자동 정제 상세 처리 로그 보기 (원본 154행 → 정제 후 150건)
바이브 코더의 현실 체감 꿀팁과 주의할 점
직접 써보면서 겪었던 현실적인 팁 두 가지만 짚어드릴게요. 첫째는 엑셀 양식의 '헤더(컬럼명)'입니다. 지점마다 '매출'이라고 쓴 곳도 있고 '판매금액'이라고 쓴 곳도 있다면 코드가 에러를 냅니다. 이럴 때는 AI에게 "지점마다 컬럼 이름이 조금씩 다른데, '매출'이나 '판매액'이라는 글자가 들어가면 전부 '매출액'으로 통일해 주는 코드도 추가해 줘"라고 한 줄만 덧붙이면 끝납니다.
둘째는 보고를 받는 상사의 취향입니다. 아무리 예쁜 웹 화면을 보여줘도 결국 "그래서 엑셀 파일은 어디 있어?"라고 묻는 상사가 꼭 계시거든요. 그래서 대시보드 우측 상단에 '정제된 통합 데이터 엑셀로 다운로드' 버튼을 코드에 꼭 넣어달라고 하세요. 대시보드로 브리핑하면서 "정제된 최종본은 여기 버튼 누르면 바로 엑셀로 떨어집니다"라고 말씀드리면 감탄사가 절로 나옵니다.
새로운 툴이나 코딩 문법을 굳이 학원 다니며 배울 필요가 전혀 없습니다. 우리가 겪는 귀찮음의 90%는 이미 세상에 나온 무료 라이브러리로 10초 만에 풀 수 있고, 그 연결 고리는 대화형 AI가 완벽하게 이어주니까요.
야근하며 손가락 아프게 마우스 휠 굴리던 시간을 이 간단한 도구 하나로 전부 털어냈습니다. 남는 시간에는 진짜 인사이트를 고민하거나, 가벼운 마음으로 정시 퇴근해서 저녁이 있는 삶을 즐겨보세요. 직장인의 시간은 회사 모니터 앞 복사-붙여넣기에 쓰기엔 너무 아까우니까요.
오늘도 비효율적인 반복 업무와 싸우느라 수고 많으셨습니다. 여러분의 빠른 칼퇴를 언제나 응원합니다!
실제 실행 전체 코드 (app.py & 실행하기.bat)
상단 시뮬레이터와 동일하게 내 PC에서 5개 지점 분산 엑셀·CSV 파일을 직접 읽어 통합·정제하고 브라우저 대시보드와 서식화된 엑셀 파일까지 생성하는 파이썬 전체 코드(app.py)와 원클릭 실행 파일(실행하기.bat)입니다.


▼ Streamlit 대시보드 전체 코드 보기 (app.py 628줄 · 클릭하여 펼치기/접기)
# ==============================================================================
# [업무 자동화 3편] 원클릭 인터랙티브 매출 대시보드 (app.py)
#
# ■ 필수 라이브러리 설치 (최초 1회):
# pip install streamlit pandas openpyxl plotly
#
# ■ 실행 방법:
# 같은 폴더의 '실행하기.bat'를 더블클릭하거나, 터미널에서 아래 명령어 실행:
# streamlit run app.py
# ==============================================================================
import glob
import io
import os
import re
from typing import Dict, List, Tuple
import openpyxl
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import streamlit as st
st.set_page_config(
page_title="전국 지점 통합 매출 대시보드",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded",
)
# 깔끔한 대시보드 스타일링 (상단 헤더 여백 확보 및 카드 디자인)
st.markdown(
"""
<style>
.block-container {
padding-top: 3.5rem;
padding-bottom: 1.5rem;
max-width: 1440px;
}
[data-testid="stSidebar"] {
background-color: #FFFFFF;
border-right: 1px solid #E2E8F0;
}
[data-testid="stSidebar"] [data-testid="stSidebarContent"] {
padding-top: 1.5rem;
}
div[data-testid="stMetric"] {
background-color: #FFFFFF;
border: 1px solid #E2E8F0;
border-radius: 12px;
padding: 13px 16px;
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
}
div[data-testid="stMetric"] label {
font-size: 0.86rem;
font-weight: 600;
color: #475569;
}
div[data-testid="stMetricValue"] {
font-size: 1.5rem;
font-weight: 800;
color: #0F172A;
}
.dashboard-title {
font-size: 1.65rem;
font-weight: 800;
color: #0F172A;
margin: 0;
line-height: 1.3;
}
.dashboard-subtitle {
font-size: 0.9rem;
color: #64748B;
margin-top: 4px;
margin-bottom: 0;
}
.chart-card-title {
font-size: 1rem;
font-weight: 700;
color: #1E293B;
margin-bottom: 0.3rem;
}
</style>
""",
unsafe_allow_html=True,
)
def read_csv_safely(file_path: str) -> pd.DataFrame:
"""한글 CSV 인코딩(utf-8-sig, cp949, euc-kr)을 순차 시도하여 안전하게 읽습니다."""
for enc in ("utf-8-sig", "cp949", "euc-kr", "utf-8"):
try:
return pd.read_csv(file_path, encoding=enc)
except UnicodeDecodeError:
continue
return pd.read_csv(file_path, encoding="utf-8", errors="replace")
def normalize_columns(df: pd.DataFrame, file_name: str, logs: List[str]) -> pd.DataFrame:
"""지점마다 조금씩 다른 컬럼명을 표준 스키마로 자동 통일합니다."""
rename_map: Dict[str, str] = {}
for col in df.columns:
col_str = str(col).strip()
if col_str in ("매출액", "주문일자", "지점명", "주문번호"):
continue
if any(k in col_str for k in ("매출", "판매액", "판매금액")):
rename_map[col] = "매출액"
elif any(k in col_str for k in ("주문일자", "거래일자", "일자", "날짜")):
rename_map[col] = "주문일자"
elif "지점" in col_str and "지점명" not in df.columns:
rename_map[col] = "지점명"
if rename_map:
detail = ", ".join(f"'{k}'→'{v}'" for k, v in rename_map.items())
logs.append(f"[{file_name}] 컬럼명 자동 통일: {detail}")
df = df.rename(columns=rename_map)
return df
def parse_mixed_date(val) -> pd.Timestamp:
"""2026-05-01, 26.5.1, 2026/05/01 등 뒤섞인 날짜 형식을 통일합니다."""
if pd.isna(val):
return pd.NaT
if isinstance(val, (pd.Timestamp,)):
return val.normalize()
text = str(val).strip()
if not text:
return pd.NaT
# 8자리 숫자 형태 (예: 20260801)
if re.fullmatch(r"d{8}", text):
return pd.to_datetime(text, format="%Y%m%d", errors="coerce")
# 구분자(., /)를 하이픈(-)으로 통일
normalized = re.sub(r"[./s]+", "-", text).strip("-")
parts = normalized.split("-")
if len(parts) == 3 and len(parts[0]) == 2 and parts[0].isdigit():
normalized = f"20{parts[0]}-{parts[1].zfill(2)}-{parts[2].zfill(2)}"
return pd.to_datetime(normalized, errors="coerce")
def clean_numeric_amount(series: pd.Series) -> Tuple[pd.Series, int]:
"""문자('원', 콤마, '미집계')나 빈칸이 섞인 금액 열을 숫자로 변환하고 오류 건은 0으로 보정합니다."""
cleaned_str = (
series.astype(str)
.str.replace(",", "", regex=False)
.str.replace("원", "", regex=False)
.str.strip()
)
cleaned_str = cleaned_str.replace({"": None, "nan": None, "None": None, "NaN": None})
numeric = pd.to_numeric(cleaned_str, errors="coerce")
invalid_count = int(numeric.isna().sum())
return numeric.fillna(0).astype(int), invalid_count
@st.cache_data(show_spinner=False)
def load_and_clean_data(input_dir: str) -> Tuple[pd.DataFrame, Dict]:
"""data_input 폴더 내 모든 .xlsx / .csv 파일을 읽어 병합하고 정제합니다."""
logs: List[str] = []
stats = {
"files_count": 0,
"file_names": [],
"raw_rows": 0,
"empty_rows_removed": 0,
"invalid_sales_fixed": 0,
"duplicates_removed": 0,
"invalid_dates_removed": 0,
"logs": logs,
}
if not os.path.isdir(input_dir):
return pd.DataFrame(), stats
all_files = sorted(
glob.glob(os.path.join(input_dir, "*.xlsx"))
+ glob.glob(os.path.join(input_dir, "*.csv"))
)
valid_files = [f for f in all_files if not os.path.basename(f).startswith("~$")]
if not valid_files:
return pd.DataFrame(), stats
frames: List[pd.DataFrame] = []
for file_path in valid_files:
file_name = os.path.basename(file_path)
if file_path.lower().endswith(".xlsx"):
df_part = pd.read_excel(file_path)
else:
df_part = read_csv_safely(file_path)
raw_len = len(df_part)
stats["raw_rows"] += raw_len
# 1) 완전 빈 행 제거
df_part = df_part.dropna(how="all")
empty_removed = raw_len - len(df_part)
if empty_removed > 0:
stats["empty_rows_removed"] += empty_removed
logs.append(f"[{file_name}] 빈 행(공백 줄) {empty_removed}건 자동 제거")
# 2) 컬럼명 자동 통일
df_part = normalize_columns(df_part, file_name, logs)
df_part["원본파일"] = file_name
frames.append(df_part)
stats["file_names"].append(file_name)
stats["files_count"] = len(frames)
combined = pd.concat(frames, ignore_index=True)
# 3) 날짜 포맷 통일 (YYYY-MM-DD)
if "주문일자" in combined.columns:
parsed_dates = combined["주문일자"].apply(parse_mixed_date)
bad_dates = int(parsed_dates.isna().sum())
if bad_dates > 0:
stats["invalid_dates_removed"] = bad_dates
logs.append(f"[날짜 정제] 해석 불가 날짜 행 {bad_dates}건 제외")
combined["주문일자_dt"] = parsed_dates
combined = combined.dropna(subset=["주문일자_dt"]).copy()
combined["주문일자"] = combined["주문일자_dt"].dt.strftime("%Y-%m-%d")
# 4) 매출액·수량·단가 숫자 정제 (오류/빈칸 -> 0)
if "매출액" in combined.columns:
combined["매출액"], fixed_cnt = clean_numeric_amount(combined["매출액"])
stats["invalid_sales_fixed"] = fixed_cnt
if fixed_cnt > 0:
logs.append(f"[매출 정제] 문자/빈칸이 섞인 매출액 {fixed_cnt}건을 0원으로 안전 보정")
for num_col in ("수량", "단가"):
if num_col in combined.columns:
combined[num_col], _ = clean_numeric_amount(combined[num_col])
# 5) 중복 주문번호 제거 (최신 입력 데이터 1건만 유지)
if "주문번호" in combined.columns:
combined["주문번호"] = combined["주문번호"].astype(str).str.strip()
before_dedup = len(combined)
combined = combined.drop_duplicates(subset=["주문번호"], keep="last")
dup_cnt = before_dedup - len(combined)
stats["duplicates_removed"] = dup_cnt
if dup_cnt > 0:
logs.append(f"[중복 제거] 중복 주문번호 {dup_cnt}건 제거 (최신 데이터 1건 유지)")
# 정렬 및 표준 컬럼 정리
if "주문일자_dt" in combined.columns:
combined = combined.sort_values(by=["주문일자_dt", "지점명"], ascending=[True, True])
standard_order = [
"주문번호",
"주문일자",
"지점명",
"담당자",
"카테고리",
"상품명",
"수량",
"단가",
"매출액",
]
ordered_cols = [c for c in standard_order if c in combined.columns]
combined = combined[ordered_cols + ["주문일자_dt"]].reset_index(drop=True)
return combined, stats
def convert_df_to_excel(df: pd.DataFrame) -> bytes:
"""정제된 데이터프레임을 깔끔한 서식이 적용된 엑셀(.xlsx) 바이트로 변환합니다."""
export_df = df.drop(columns=["주문일자_dt"], errors="ignore").copy()
output = io.BytesIO()
with pd.ExcelWriter(output, engine="openpyxl") as writer:
export_df.to_excel(writer, index=False, sheet_name="통합_매출_데이터")
ws = writer.sheets["통합_매출_데이터"]
ws.views.sheetView[0].showGridLines = True
header_fill = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
header_font = Font(name="맑은 고딕", size=10, bold=True, color="FFFFFF")
data_font = Font(name="맑은 고딕", size=10)
thin_border = Border(
left=Side(style="thin", color="CBD5E1"),
right=Side(style="thin", color="CBD5E1"),
top=Side(style="thin", color="CBD5E1"),
bottom=Side(style="thin", color="CBD5E1"),
)
ws.row_dimensions[1].height = 25
for col_idx in range(1, len(export_df.columns) + 1):
cell = ws.cell(row=1, column=col_idx)
cell.fill = header_fill
cell.font = header_font
cell.alignment = Alignment(horizontal="center", vertical="center")
cell.border = thin_border
for row_idx in range(2, len(export_df) + 2):
ws.row_dimensions[row_idx].height = 20
for col_idx, col_name in enumerate(export_df.columns, start=1):
cell = ws.cell(row=row_idx, column=col_idx)
cell.font = data_font
cell.border = thin_border
if col_name in ("수량", "단가", "매출액"):
cell.alignment = Alignment(horizontal="right", vertical="center")
cell.number_format = "#,##0"
elif col_name in ("주문번호", "주문일자", "지점명", "담당자", "카테고리"):
cell.alignment = Alignment(horizontal="center", vertical="center")
else:
cell.alignment = Alignment(horizontal="left", vertical="center")
for col in ws.columns:
max_len = 0
col_letter = get_column_letter(col[0].column)
for cell in col:
val = str(cell.value or "")
width = sum(2 if ord(ch) > 127 else 1 for ch in val)
if width > max_len:
max_len = width
ws.column_dimensions[col_letter].width = max(max_len + 4, 12)
return output.getvalue()
def main():
current_dir = os.path.dirname(os.path.abspath(__file__))
input_dir = os.path.join(current_dir, "data_input")
df, stats = load_and_clean_data(input_dir)
if df.empty:
st.error(
"⚠️ `data_input` 폴더에서 읽어올 엑셀(.xlsx) 또는 CSV(.csv) 파일을 찾지 못했습니다.\n\n"
f"확인 경로: `{input_dir}`"
)
st.stop()
# --------------------------------------------------------------------------
# 좌측 사이드바: 지점 · 기간 · 카테고리 필터
# --------------------------------------------------------------------------
with st.sidebar:
st.markdown("### 🎛️ 대시보드 필터 설정")
st.caption(f"📁 `data_input` ({stats['files_count']}개 파일 자동 연동)")
all_branches = sorted(df["지점명"].dropna().unique().tolist())
selected_branches = st.multiselect(
"🏢 지점명 선택",
options=all_branches,
default=all_branches,
placeholder="분석할 지점을 선택하세요",
)
min_date = df["주문일자_dt"].min().date()
max_date = df["주문일자_dt"].max().date()
selected_dates = st.date_input(
"📅 조회 기간",
value=(min_date, max_date),
min_value=min_date,
max_value=max_date,
)
if "카테고리" in df.columns:
all_categories = sorted(df["카테고리"].dropna().unique().tolist())
selected_categories = st.multiselect(
"🗂️ 품목 카테고리",
options=all_categories,
default=all_categories,
)
else:
selected_categories = []
trend_unit = st.radio(
"📈 추이 그래프 집계 기준",
options=["일별 추이", "월별 추이"],
index=0,
horizontal=True,
)
st.markdown("---")
st.markdown("##### 🧹 자동 정제 요약")
st.info(
f"• 병합 파일: **{stats['files_count']}개** · 빈 행 제거: **{stats['empty_rows_removed']}건**\n\n"
f"• 중복 제거: **{stats['duplicates_removed']}건** · 오류 보정: **{stats['invalid_sales_fixed']}건**"
)
# 날짜 범위 파싱 (단일 날짜 선택 시에도 에러 방지)
if isinstance(selected_dates, (tuple, list)):
if len(selected_dates) == 2:
start_date, end_date = selected_dates
elif len(selected_dates) == 1:
start_date = end_date = selected_dates[0]
else:
start_date, end_date = min_date, max_date
else:
start_date = end_date = selected_dates
# 필터링 적용
mask = (
df["지점명"].isin(selected_branches)
& (df["주문일자_dt"].dt.date >= start_date)
& (df["주문일자_dt"].dt.date <= end_date)
)
if selected_categories and "카테고리" in df.columns:
mask = mask & df["카테고리"].isin(selected_categories)
filtered_df = df.loc[mask].copy()
# --------------------------------------------------------------------------
# 우측 상단: 대시보드 헤더 + 정제된 통합 엑셀 다운로드 버튼
# --------------------------------------------------------------------------
header_col1, header_col2 = st.columns([3.0, 1.3], vertical_alignment="center")
with header_col1:
st.markdown(
'<p class="dashboard-title">📊 전국 지점 통합 매출 분석 대시보드</p>'
f'<p class="dashboard-subtitle">조회 기간: {start_date} ~ {end_date} | '
f'선택 지점: {len(selected_branches)}/{len(all_branches)}개 지점 실시간 반영</p>',
unsafe_allow_html=True,
)
with header_col2:
if not filtered_df.empty:
excel_bytes = convert_df_to_excel(filtered_df)
st.download_button(
label="📥 정제된 통합 데이터 엑셀로 다운로드",
data=excel_bytes,
file_name=f"정제된_통합매출_{start_date}_{end_date}.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
type="primary",
use_container_width=True,
)
if filtered_df.empty:
st.warning("선택하신 필터 조건에 해당하는 매출 데이터가 없습니다. 좌측 필터를 조정해 주세요.")
st.stop()
st.markdown("<div style='height: 10px;'></div>", unsafe_allow_html=True)
# --------------------------------------------------------------------------
# 상단 KPI 카드 4종
# --------------------------------------------------------------------------
total_sales = int(filtered_df["매출액"].sum())
order_count = int(len(filtered_df))
avg_order = int(round(total_sales / order_count)) if order_count else 0
branch_summary = (
filtered_df.groupby("지점명", as_index=False)["매출액"]
.sum()
.sort_values("매출액", ascending=False)
)
top_branch = branch_summary.iloc[0]["지점명"]
top_branch_share = (
(branch_summary.iloc[0]["매출액"] / total_sales * 100) if total_sales > 0 else 0.0
)
kpi1, kpi2, kpi3, kpi4 = st.columns(4)
kpi1.metric(
"💰 총 매출액",
f"{total_sales:,}원",
f"선택 {len(selected_branches)}개 지점 합계",
delta_color="off",
delta_arrow="off",
)
kpi2.metric(
"📦 총 주문 건수",
f"{order_count:,}건",
f"중복 {stats['duplicates_removed']}건 정제 완료",
delta_color="off",
delta_arrow="off",
)
kpi3.metric(
"🧾 건당 평균 객단가",
f"{avg_order:,}원",
f"총 수량 {int(filtered_df['수량'].sum()):,}개",
delta_color="off",
delta_arrow="off",
)
kpi4.metric(
"🏆 최고 매출 지점",
top_branch,
f"전체 매출의 {top_branch_share:.1f}%",
delta_color="normal",
delta_arrow="off",
)
st.markdown("<div style='height: 10px;'></div>", unsafe_allow_html=True)
# --------------------------------------------------------------------------
# 중단 반응형 차트 2종 (매출 추이 꺾은선 그래프 + 지점별 점유율 도넛 차트)
# --------------------------------------------------------------------------
chart_col1, chart_col2 = st.columns([1.45, 1.0])
with chart_col1:
with st.container(border=True):
if trend_unit == "일별 추이":
trend_df = (
filtered_df.groupby("주문일자", as_index=False)["매출액"]
.sum()
.sort_values("주문일자")
)
x_col = "주문일자"
chart_title = "📈 일별 매출 추이 (꺾은선 그래프)"
x_hover = "%{x|%Y-%m-%d}"
else:
monthly_source = filtered_df.assign(
주문월=filtered_df["주문일자_dt"].dt.strftime("%Y-%m")
)
trend_df = (
monthly_source.groupby("주문월", as_index=False)["매출액"]
.sum()
.sort_values("주문월")
)
x_col = "주문월"
chart_title = "📈 월별 매출 추이 (꺾은선 그래프)"
x_hover = "%{x}"
st.markdown(f'<div class="chart-card-title">{chart_title}</div>', unsafe_allow_html=True)
fig_line = go.Figure()
fig_line.add_trace(
go.Scatter(
x=trend_df[x_col],
y=trend_df["매출액"],
mode="lines+markers",
line=dict(color="#2563EB", width=2.8),
marker=dict(size=6.5 if trend_unit == "일별 추이" else 10, color="#1D4ED8"),
fill="tozeroy",
fillcolor="rgba(37, 99, 235, 0.08)",
hovertemplate=f"<b>{x_hover}</b><br>매출액: %{{y:,.0f}}원<extra></extra>",
)
)
xaxis_cfg = dict(
title="",
showgrid=False,
tickfont=dict(size=11, color="#475569"),
type="category" if trend_unit == "월별 추이" else "date",
)
if trend_unit == "일별 추이":
xaxis_cfg["tickformat"] = "%m/%d"
else:
xaxis_cfg["range"] = [-0.2, max(len(trend_df) - 0.8, 0.2)]
fig_line.update_layout(
height=320,
margin=dict(l=14, r=22, t=10, b=8),
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
xaxis=xaxis_cfg,
yaxis=dict(
title="",
gridcolor="#F1F5F9",
tickformat=",",
ticksuffix="원",
tickfont=dict(size=11, color="#475569"),
),
hovermode="x unified",
)
st.plotly_chart(fig_line, use_container_width=True)
with chart_col2:
with st.container(border=True):
st.markdown(
'<div class="chart-card-title">🍩 지점별 매출 점유율 (도넛 차트)</div>',
unsafe_allow_html=True,
)
palette = ["#1D4ED8", "#0284C7", "#059669", "#D97706", "#7C3AED"]
fig_donut = px.pie(
branch_summary,
names="지점명",
values="매출액",
hole=0.48,
color_discrete_sequence=palette,
)
fig_donut.update_traces(
textposition="inside",
textinfo="label+percent",
textfont=dict(size=11.5, color="white"),
hovertemplate="<b>%{label}</b><br>매출액: %{value:,.0f}원 (%{percent})<extra></extra>",
)
fig_donut.update_layout(
height=320,
margin=dict(l=8, r=8, t=8, b=8),
paper_bgcolor="rgba(0,0,0,0)",
legend=dict(
orientation="h",
yanchor="bottom",
y=-0.15,
xanchor="center",
x=0.5,
font=dict(size=11),
),
annotations=[
dict(
text=f"<b>{len(branch_summary)}개 지점</b>",
x=0.5,
y=0.5,
font_size=13,
font_color="#334155",
showarrow=False,
)
],
)
st.plotly_chart(fig_donut, use_container_width=True)
# --------------------------------------------------------------------------
# 하단: 정제된 통합 데이터 테이블 및 정제 처리 로그
# --------------------------------------------------------------------------
display_df = filtered_df.drop(columns=["주문일자_dt"], errors="ignore").sort_values(
by=["주문일자", "지점명"], ascending=[False, True]
)
st.markdown("#### 📋 정제된 통합 매출 데이터 미리보기")
st.dataframe(
display_df,
use_container_width=True,
hide_index=True,
height=270,
column_config={
"수량": st.column_config.NumberColumn("수량", format="%d개"),
"단가": st.column_config.NumberColumn("단가", format="%,d원"),
"매출액": st.column_config.NumberColumn("매출액", format="%,d원"),
},
)
with st.expander("🔍 데이터 자동 정제 상세 처리 로그 확인하기"):
if stats["logs"]:
for line in stats["logs"]:
st.write(f"- {line}")
else:
st.write("모든 파일의 양식과 데이터가 이미 표준과 일치합니다.")
if __name__ == "__main__":
main()
▼ 원클릭 실행 배치파일 코드 보기 (실행하기.bat · 클릭하여 펼치기/접기)
@echo off
chcp 65001 > nul
cd /d "%~dp0"
title [전자동 3편] 원클릭 매출 대시보드 실행기
echo ============================================================
echo [전자동 업무 자동화 3편] Streamlit 원클릭 매출 대시보드
echo ============================================================
echo.
echo [1/2] 필수 파이썬 라이브러리 확인 중...
python -c "import streamlit, pandas, openpyxl, plotly" 2>nul
if errorlevel 1 (
echo - 필수 패키지를 최초 1회 자동 설치합니다. 잠시만 기다려 주세요...
pip install streamlit pandas openpyxl plotly
)
echo [2/2] 대시보드 서버를 시작합니다. 잠시 후 브라우저가 열립니다!
echo ※ 종료하려면 이 창을 닫거나 Ctrl+C를 누르세요.
echo ============================================================
echo.
python -m streamlit run app.py
pause
전국 5개 지점의 실제 분산 엑셀 파일들(data_input)과 클릭 한 번으로 웹 브라우저를 띄워주는 대시보드 코드(app.py), 그리고 원클릭 실행 배치파일(실행하기.bat)을 모두 담았습니다. 다운받아 압축 풀고 '실행하기.bat'를 마우스로 더블클릭만 해보세요!
※ 압축을 푼 뒤 '읽어보세요_3편_사용법.txt'를 열면 초보자용 실행 안내가 상세히 적혀 있습니다.
업무 자동화 시리즈 이전 편 보기
'AI 실생활 웹앱 개발기 > For 업무' 카테고리의 다른 글
| 코딩 한 줄 없이 AI 직원 3명 고용하기? 서브에이전트 실무 세팅법 (0) | 2026.11.12 |
|---|---|
| "대외비라 챗GPT 못 쓰는데…" 사내망에서도 안전한 공문서 글자수·표기법 교정기 만들기 (0) | 2026.11.10 |
| 복붙만 2시간 하던 단체 메일, 클릭 한 번으로 끝냅니다 (이름·금액 자동 매칭) (0) | 2026.11.08 |
| [업무 자동화] 빈칸, 중복값, 오타 골치 아픈 빅데이터, AI 명령어로 말끔하게 정제하기 (0) | 2026.11.01 |
| [업무 자동화] 폴더에 던져두면 끝! 매주 흩어진 엑셀 파일 30개 10초 만에 하나로 합치기 (0) | 2026.11.01 |