Skip to content

Commit 0661266

Browse files
authored
XLSX 2016 to SQL DB
This python3 code can convert a 2016 XLSX Workbook {with many sheets} to a SQL Database {with respective tables}.
1 parent 124d7b0 commit 0661266

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

exceltosql.py

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Mon Sep 17 06:28:21 2018
4+
5+
@author: LALIT ARORA
6+
"""
7+
8+
import sqlite3
9+
import openpyxl
10+
11+
def create_connection(db_file):
12+
try:
13+
conn = sqlite3.connect(db_file)
14+
return conn
15+
except:
16+
print("Database connection Error!")
17+
return None
18+
19+
def u_create_table(wbk,db_file):
20+
wb=openpyxl.load_workbook(wbk)
21+
sheets=wb.sheetnames
22+
for i in range(len(sheets)):
23+
columns=[]
24+
ac_sheet=wb[sheets[i]]
25+
cols = ac_sheet.max_column
26+
for j in range(1,cols+1):
27+
temp=(ac_sheet.cell(row=1, column=j).value)
28+
if temp is not None:
29+
columns.append("%r"%str(temp))
30+
print(columns)
31+
create_table(columns,sheets[i],db_file)
32+
transfer_data(columns,sheets[i],db_file,wbk)
33+
34+
def create_table(cols,sheetname,dbname):
35+
if len(cols)==0:
36+
return
37+
data="CREATE TABLE IF NOT EXISTS "+str(sheetname)+" ( "
38+
for i in range(len(cols)):
39+
data=data+str(cols[i])+" text, "
40+
data=data[:len(data)-2]
41+
data=data+" );"
42+
conn=create_connection(dbname)
43+
c = conn.cursor()
44+
c.execute(data)
45+
conn.commit()
46+
conn.close()
47+
48+
def transfer_data(cols,sheetname,dbname,wbk):
49+
if len(cols)==0:
50+
return
51+
wb=openpyxl.load_workbook(wbk)
52+
ac_sheet=wb[sheetname]
53+
rows=ac_sheet.max_row
54+
var=",".join(cols)
55+
var="INSERT INTO "+str(sheetname)+" ("+var+") VALUES ("
56+
57+
conn=create_connection(dbname)
58+
c=conn.cursor()
59+
for i in range(2,rows+1):
60+
vals=[]
61+
for j in range(1,len(cols)+1):
62+
vals.append('"'+str(ac_sheet.cell(row=i, column=j).value)+'"')
63+
e_vals=",".join(vals)
64+
e_vals=e_vals+")"
65+
c.execute(var+e_vals)
66+
conn.commit()
67+
conn.close()
68+
69+
70+
if __name__ == '__main__':
71+
import sys
72+
arguments=sys.argv
73+
wbk=arguments[1]
74+
db_file = arguments[2]
75+
print("Working..")
76+
u_create_table(wbk,db_file)
77+
print ("Complete..")

0 commit comments

Comments
 (0)