Spaces:
Sleeping
Sleeping
File size: 3,348 Bytes
7b1cbee |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
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 (TEXT)',
'float' : 'Float (REAL)',
'int' : 'Integer (INT)',
'datetime': 'Datetime (TEXT)',
'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
# μλ 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':
if df[column].dtypes == float or df[column].dtypes == int:
df[column] = df[column].astype(str).str.replace('.0','')
else:
df[column] = df[column]
next = True
if next:
# sql lite λ°μ΄ν°λ² μ΄μ€ μ°κ²° λ° μμ±
conn = sqlite3.connect(file_name)
c = conn.cursor()
# λ°μ΄ν°νλ μμ SQLν
μ΄λΈλ‘ λ³ν
df.to_sql(f'{file_name}', conn, dtype = selected_data_types, if_exists = 'replace', index = False)
st.success(f'νμΌμ μ±κ³΅μ μΌλ‘ λ°μ΄ν°λ² μ΄μ€λ‘ μ μ₯λμμ΅λλ€. λ°μ΄ν°λ² μ΄μ€λͺ
[{file_name}]')
# μ°κ²° μ’
λ£
conn.close()
|