-
Notifications
You must be signed in to change notification settings - Fork 0
/
Excel2db.py
180 lines (152 loc) · 6.41 KB
/
Excel2db.py
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# -*- coding: utf-8 -*-
# @Time : 2019/1/27 下午4:11
# @Author : shiwei-Du
# @Email : [email protected]
# @File : Excel2db.py
# @Software: PyCharm
import sys
import pandas as pd
from sqlalchemy import create_engine
import configparser
import threading
import argparse
import os
from lib.Log import Log
config = configparser.ConfigParser()
config.read('config/define.ini')
dbconfig = config['MYSQL']
handle = "%s+%s://%s:%s@%s:%s/%s?charset=%s" % (dbconfig['DIALECT'], dbconfig['DRIVER'], dbconfig['USER'],
dbconfig['PASSWORD'], dbconfig['HOST'], dbconfig['PORT'],
dbconfig['DBNAME'], dbconfig['CHARSET'])
engine = create_engine(handle)
class Excel2db(Log):
def __init__(self):
Log.__init__(self)
self.path = config.get('EXCEL_CONFIG', 'SOURCE_PATH')
self.back_path = config.get('EXCEL_CONFIG', 'BACKUPS_PATH')
def load_in_by_table(self, table:str):
try:
df = pd.read_excel(self.path + table + '.xls', index_col=None)
except Exception as e:
msg = 'Read %s Error, Error is:%s' % (table, str(e))
self.error(msg)
return
try:
chunksize = dbconfig['CHUNKSIZE']
if chunksize != 'None':
chunksize = int(dbconfig['CHUNKSIZE'])
else:
chunksize = None
df.to_sql(table, engine, if_exists=dbconfig['IF_EXISTS'], index=0, chunksize=chunksize)
except Exception as e:
msg = 'import %s Error, Error is:%s' % (table, str(e))
self.error(msg)
return
self.info('Table:% s Success load In' % table)
return True
def load_out_by_table(self, table:str):
try:
df = pd.read_sql_table(table, engine)
except Exception as e:
self.info('Select %s Error, Error is:%s' % (table, str(e)))
return
try:
df.to_excel(self.back_path + table + ".xls")
except Exception as e:
self.error('import %s Error, Error is:%s' % (table, str(e)))
return
self.info('Table:% s Success load out' % table)
return True
def get_all_table_names(self):
try:
sql = "select table_name from information_schema.TABLES where TABLE_SCHEMA='%s' ;" % dbconfig['DBNAME']
df = pd.read_sql(sql, engine)
except Exception as e:
self.error('Error is:%s' % (str(e)))
return
return [table[0] for table in df.values]
def get_all_files_name(self):
try:
tables = []
if not os.path.exists(self.path):
self.error('Source Path Not Exists!!!')
pass
for file in os.listdir(self.path):
if file.endswith(".xls"):
table=file[:-4]
tables.append(table)
except Exception as e:
self.error('Scan %s Error, Error is: %s' % (self.path, str(e)))
return
return tables
def load_out_all(self):
all_tables = self.get_all_table_names()
if all_tables:
self.create_thread(all_tables, self.load_out_by_table)
def load_in_all(self):
all_tables = self.get_all_files_name()
# print(all_tables)
if all_tables:
self.create_thread(all_tables, self.load_in_by_table)
else:
self.error('No File Match')
def create_thread(self, all_tables, func):
for tb in all_tables:
t = threading.Thread(target=func, args=(tb,)) # 创建线程
t.start()
def check_dir(self):
try:
if not os.path.isdir(self.back_path):
os.makedirs(self.back_path, mode=755)
except Exception as e:
self.error('Mkdirs %s error, error is:%s' % (self.back_path, str(e)))
exit()
if __name__ == '__main__':
if sys.version_info < (3, 0):
print('Python Version is too low')
exit()
'''
The description parameter can be used to insert information describing script usage, which can be empty.
Notice: formatter_class ,The purpose is to describe parameters too long without field newlines
'''
parser = argparse.ArgumentParser(description="Database and Excel Interoperate", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--version', '-v', action='version', version="%(prog)s " + config['VERSION']['version'])
parser.add_argument('--operation', '-opt', type=int, help="Operation Detail:\n"
" 1:Load In Single Table By Table Excel Name\n"
" 2:Load Out Single Table By Table Name\n"
" 3:Load In All Files By Configure Source Path\n"
" 4:Load Out All Tables By Configure Dbname\n"
, choices=[1, 2, 3, 4], required=True)
parser.add_argument('--table', '-t', default=None, help="Table Params Details\n"
" 1.The name of the Excel to be operated:\n"
" 2.There must be corresponding table names \n"
" in the configured database.\n"
" (When the name of the input table is empty, \n"
" all tables in the configuration database \n"
" are operated by default. )")
args = parser.parse_args()
if not args.operation:
print("Please Select Operation number....")
exit()
obj = Excel2db()
operation = args.operation
if operation == 1:
table = args.table
if table:
obj.check_dir()
obj.load_in_by_table(table)
else:
pass
elif operation == 2:
table = args.table
if table:
obj.load_out_by_table(table)
else:
pass
elif operation == 3:
obj.load_in_all()
elif operation == 4:
obj.check_dir()
obj.load_out_all()
else:
print('Operation Failed!!!')