Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import pandas as pd | |
| import sqlite3 | |
| import os | |
| from datetime import datetime | |
| def app(): | |
| st.title('Excel to DataBase') | |
| st.write('μμ μ λ£μ΄ λ°μ΄ν°λ² μ΄μ€λ₯Ό λ§λ€μ΄λ΄ μλ€.') | |
| file_name = st.text_input('νμΌλͺ μ§μ νκΈ°') | |
| # μμ νμΌ μ λ‘λ | |
| uploaded_file = st.file_uploader('Choose an Excel file', type = ['xlsx','xls','csv']) | |
| if uploaded_file is not None: | |
| # μμ νμΌμ λ°μ΄ν°νλ μμΌλ‘ λ³ν | |
| try: | |
| df = pd.read_csv(uploaded_file) | |
| except: | |
| df = pd.read_excel(uploaded_file) | |
| # κ° μ΄μ λν λ°μ΄ν° νμ μ ν μ΅μ μ 곡 | |
| data_types = {'object': 'String', | |
| 'float' : 'Float', | |
| 'int' : 'Integer', | |
| 'datetime': 'Datetime', | |
| 'bool' : 'Bool', | |
| } | |
| selected_data_types = {} | |
| for column in df.columns: | |
| data_type = st.selectbox(f"SELECT data type for column '{column}'", | |
| options = list(data_types.keys()), | |
| format_func = lambda x : data_types[x], | |
| key = column) | |
| selected_data_types[column] = data_type | |
| print(selected_data_types) | |
| # μλ int / float κ²λ€ μ€μμ object λ‘ λ³νν΄μΌ ν κ²λ€μ object λ‘ λ°κΎΈμ΄μ£ΌκΈ° | |
| if st.button('λ°μ΄ν° λ³ννκ³ μ μ₯νκΈ°'): | |
| for column, data_type in selected_data_types.items(): | |
| if data_type == 'float': | |
| try: | |
| df[column] = df[column].str.replace(',','') | |
| except: | |
| continue | |
| df[column] = pd.to_numeric(df[column], errors = 'coerce') | |
| elif data_type == 'int': | |
| try: | |
| df[column] = df[column].str.replace(',','') | |
| except: | |
| continue | |
| df[column] = pd.to_numeric(df[column].str.replace(',',''), errors = 'coerce').fillna(0).astype(int) | |
| elif data_type == 'datetime': | |
| df[column] = pd.to_datetime(df[column], errors = 'coerce') | |
| elif data_type == 'bool': | |
| df[column] = df[column].astype(bool) | |
| elif data_type == 'object': | |
| df[column] = df[column].astype(str).str.replace('.0','') | |
| next = True | |
| if next: | |
| # sql lite λ°μ΄ν°λ² μ΄μ€ μ°κ²° λ° μμ± | |
| conn = sqlite3.connect(file_name) | |
| c = conn.cursor() | |
| # λ°μ΄ν°νλ μμ SQLν μ΄λΈλ‘ λ³ν | |
| df.to_sql(f'{file_name}', conn, if_exists = 'replace', index = False) | |
| st.success(f'νμΌμ μ±κ³΅μ μΌλ‘ λ°μ΄ν°λ² μ΄μ€λ‘ μ μ₯λμμ΅λλ€. λ°μ΄ν°λ² μ΄μ€λͺ [{file_name}]') | |
| # μ°κ²° μ’ λ£ | |
| conn | |
| conn.close() | |