如何将excel文件导入SQL Alchemy?

时间:2016-12-04 03:17:20

标签: mysql flask sqlalchemy pyexcel

我有这个代码将Excel数据导入到SQLlite中,但想知道如何将其转换为SQLAlchemy,而不是手动命名字段。

我不确定如何自动从SQLAlchemy中的Excel列字段创建字段和架构。

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()

0 个答案:

没有答案