I have this code to import Excel data into SQLlite, but wondering how to do it into SQLAlchemy instead, without naming the fields manually.
Am not sure how to create the fields and schema automatically from Excel column fields in SQLAlchemy.
con = sqlite3.connect('test237.db')
wb = load_workbook(filename=r'test.xlsx')
sheets = wb.get_sheet_names()
for sheet in sheets:
ws = wb[sheet]
columns= []
query = 'CREATE TABLE ' + str(sheet) + '(ID INTEGER PRIMARY KEY AUTOINCREMENT'
for row in ws.rows[0]:
query += ', ' + row.value + ' TEXT'
columns.append(row.value)
query += ');'
con.execute(query)
tup = []
for i, rows in enumerate(ws):
tuprow = []
for row in rows:
tuprow.append(unicode(row.value).strip()) if unicode(row.value).strip() != 'None' else tuprow.append('')
tup.append(tuple(tuprow))
insQuery1 = 'INSERT INTO ' + str(sheet) + '('
insQuery2 = ''
for col in columns:
insQuery1 += col + ', '
insQuery2 += '?, '
insQuery1 = insQuery1[:-2] + ') VALUES('
insQuery2 = insQuery2[:-2] + ')'
insQuery = insQuery1 + insQuery2
con.execute(insQuery, tup)
con.close()