Skip to content

Instantly share code, notes, and snippets.

@2chanhaeng
Last active August 27, 2024 02:10
Show Gist options
  • Select an option

  • Save 2chanhaeng/32090747434df48a2396c7abfad1ca48 to your computer and use it in GitHub Desktop.

Select an option

Save 2chanhaeng/32090747434df48a2396c7abfad1ca48 to your computer and use it in GitHub Desktop.
Convert excel files (*.xlsx) to DB data (sqlite) using pandas
# !pip install openpyxl pandas
# Note: This code is written under the assumption that
# the schema of all data in the Excel file and sheet is the same.
# 알림: 이 코드는 엑셀 파일과 시트 내 모든 데이터의 스키마가 동일하다는 가정하에 작성되었습니다.
import sqlite3
from pathlib import Path
import pandas as pd
# Set the path to the directory where
# the Excel files are stored and the name of the database file
# 엑셀 파일이 저장된 경로와 데이터베이스 파일명을 설정
EXCELS_PATH = "xlsx" # Path where the Excel files are located 엑셀 파일이 있는 경로
DB_PATH = "data.db" # Path of the SQLite database file to be saved 저장할 SQLite 데이터베이스 경로
TABLE_NAME = "Table" # Name of the SQLite database table 데이터베이스 테이블명
def main():
# Connect to the SQLite database
# SQLite 데이터베이스 연결
with sqlite3.connect(DB_PATH) as conn:
# Process all Excel files in the specified path
# 경로 내 모든 엑셀 파일 처리
process_all_excel_files(EXCELS_PATH, conn)
# Commit berfore closing the connection
# 연결을 닫기 전에 커밋
conn.commit()
# Find and process all .xlsx files in the specified path
# 경로 내 모든 .xlsx 파일을 찾고 처리
def process_all_excel_files(path: str, conn: sqlite3.Connection):
for filename in Path(path).glob("*.xlsx"):
print(f"Processing {filename}...")
save_excel_to_sqlite(filename, conn)
# Save Excel files to SQLite
# 엑셀 파일을 SQLite에 저장
def save_excel_to_sqlite(path: Path, conn: sqlite3.Connection):
# Read the Excel file
# 엑셀 파일 읽기
xls = pd.read_excel(path, None, engine="openpyxl")
for df in xls.values():
# Add the DataFrame to the SQLite table
# 데이터프레임을 SQLite 테이블에 추가
df.to_sql(TABLE_NAME, conn, if_exists="append", index=False)
conn.commit()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment