sqlor/dataloader/dataloader.py

62 lines
1.2 KiB
Python
Raw Normal View History

2019-08-21 09:26:46 +08:00
import openpyxl as xlsx
import asyncio
2023-04-11 15:12:10 +08:00
from sqlor.dbpools import DBPools
2019-08-21 09:26:46 +08:00
class CBObject:
2023-04-11 15:12:10 +08:00
def __init__(self,db, name):
self.db = db
2019-08-21 09:26:46 +08:00
self.tbl = name
2023-04-11 15:12:10 +08:00
async def handle(self,ws):
db = DBPools()
meta = sor.I()
async with db.sqlorContext(self.db) as sor:
for rec in getRecord(ws):
sor.C(self.tbl, rec)
2019-08-21 09:26:46 +08:00
typesconv = {
"int":int,
"float":float,
"str":str,
}
2023-04-11 15:12:10 +08:00
async def getRecord(ws):
2019-08-21 09:26:46 +08:00
names = []
types = []
for i,r in enumerate(ws.rows):
if i==0:
for j,c in enumerate(r):
nt = c.value.split(':')
if len(nt) < 2:
nt.append('')
n,t = nt
names.append(n)
types.append(t)
else:
dic = {}
for j,c in enumerate(r):
tf = typesconv.get(types[j],None)
v = c.value
dic[names[j]] = v
2023-04-11 15:12:10 +08:00
yield rec
2019-08-21 09:26:46 +08:00
async def excel2db(xlsxfile):
wb = xlsx.load_workbook(xlsxfile)
2023-04-11 15:12:10 +08:00
dbname = [ i[2:-3] for i in wb.sheetnames if i.startswith('__')[0]
2019-08-21 09:26:46 +08:00
for name in wb.sheetnames:
2023-04-11 15:12:10 +08:00
if name.startswith('__'):
continue
2019-08-21 09:26:46 +08:00
ws = wb[name]
2023-04-11 15:12:10 +08:00
cbobj = CBObject(dbname, name)
await cbobj.handle(ws)
2019-08-21 09:26:46 +08:00
if __name__ == '__main__':
import sys
2023-04-11 15:12:10 +08:00
config = getConfig()
DBPools(config.databases)
2019-08-21 09:26:46 +08:00
if len(sys.argv) < 2:
print('%s xlsxfile' % sys.argv[0])
sys.exit(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(excel2db(sys.argv[1]))