简体   繁体   中英

python sqlite3 creating a DB from excel

I'm trying to create a DB from an excel spreadsheet. I have the below code, the issue is when i run my code my database creates a table for each column. I would like to create a table for each spreadsheet listed in the workbook. sheet names are sheet1 and sheet2.

import sqlite3
import pandas as pd
filename="script"
con=sqlite3.connect(filename+".db")
wb=pd.read_excel(filename+'.xlsx',sheet_name='sheet1')
for sheet in wb:
wb[sheet].to_sql(sheet,con, index=False)
con.commit()
con.close()

Passing sheetname=None will give you an OrderedDict with keys of the sheet name and values as dataframes, you then loop over that.

import pandas as pd
import sqlite3

db = sqlite3.connect(':memory:')
dfs = pd.read_excel('somefile.xlsx', sheet_name=None)
for table, df in dfs.items():
    df.to_sql(table, db)
import sqlite3
import pandas as pd
filename="script"
con=sqlite3.connect(filename+".db")
wb=pd.ExcelFile(filename+'.xlsx')
for sheet in wb.sheet_names:
        df=pd.read_excel(filename+'.xlsx',sheetname=sheet)
        df.to_sql(sheet,con, index=False,if_exists="replace")
con.commit()
con.close()

Get the sheetnames first and then read the sheets and write to sqlite as given above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM