Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 인터넷안되는문제해결
- PID4
- MSSQL #TCP/IP Enabled
- CapsLock키보드 뽑기
- 한글2 #hangul2_from_2024_01_17
- IT제어
- ubunto #네티워크설정
- PHP4
- windows19Server
- CenOS6.10
- utf8mb4
- 에디트플러스 #sftp안될때
- 조성남
- centos7
- putty
- root직접로그인
- 윈도우앱지우기
- winscp
- ftp
- php7
- sftp
- 신바람여비서win98
- 코드라마 #AI
- 아이티제어
Archives
- Today
- Total
아이티제어
xlsx파일 업로드 하여 DB로 가져오는법 본문
<?php exec("python3 ./_xlsx.py.php -f /tmp/myfile.xls -d myDbName ", $output) ;
import mysql.connector
import pandas as pd
import getopt
import sys
def main(argv):
inputfile = ''
dbname = ''
try:
opts, args = getopt.getopt(argv, "hf:d:", ["file=", "dbname="])
except getopt.GetoptError:
print('_xlsx.py -f <inputfile> -d <dbname>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('_xlsx.py -f <inputfile> -d <dbname>')
sys.exit()
elif opt in ("-f", "--file"):
inputfile = arg
elif opt in ("-d", "--dbname"):
dbname = arg
print('Input file is', inputfile)
print('DB name is', dbname)
# Connect to the database
conn = mysql.connector.connect(
host='localhost',
user='root',
password='apmsetup',
database=dbname
)
cursor = conn.cursor()
# Read Excel file and create table
table_name = inputfile.split(".")[0]
df = pd.read_excel(inputfile, sheet_name=0)
# Create the table with columns
columns = ', '.join(['`{}` varchar(100) not null default \'\' '.format(col) for col in df.columns])
create_table_query = 'CREATE TABLE if not exists `{}` (idx int(11) AUTO_INCREMENT PRIMARY KEY, {}) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;'.format(table_name, columns)
cursor.execute(create_table_query)
result = cursor.fetchall()
print("Create table result = ", result)
cursor.execute("truncate {}".format(table_name))
colIns = ', '.join(['`{}` '.format(col) for col in df.columns])
# Use for loop to insert values into the table for each row
for index, row in df.iterrows():
values = ', '.join([f"'{str(value).replace('nan', '')}'" for value in row.values])
sql = f"INSERT INTO `{table_name}` ({colIns}) VALUES ({values});"
cursor.execute(sql)
result = cursor.fetchall()
print("Insert result = ", result)
# Commit the changes
conn.commit()
# Close the cursor and connection
cursor.close()
conn.close()
if __name__ == "__main__":
main(sys.argv[1:])
python3 _xlsx.py -f 파일경로/파일이름.xlsx -d 데이터베이스이름
-f와 -d 옵션 뒤에 각각 파일 경로 및 이름과 데이터베이스 이름을 입력하시면 됩니다.
'Linux > AI인공지능ChatGPT' 카테고리의 다른 글
데커 사용법 윈도우, 우분투 , 센트OS 7 비교해서 (0) | 2023.03.30 |
---|---|
Power BI를 쓰면 안되는 이유 (0) | 2023.02.26 |
이지빌더 프로 메크로 작성을 ai를 통해 해보자. (0) | 2023.02.19 |
이지빌더 프로 메크로 작성을 ai를 통해 해보자. (0) | 2023.02.19 |
전자기파가 자연 현상임을 ??? 기것 자연현상임을 설명해서 어쩌겠다고.. 지금에 AI까지 나오게 되었냐? (0) | 2023.02.18 |