Skip to content

Instantly share code, notes, and snippets.

@a-milogradov
Created November 17, 2014 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-milogradov/8b8b53d4f58d4033effa to your computer and use it in GitHub Desktop.
Save a-milogradov/8b8b53d4f58d4033effa to your computer and use it in GitHub Desktop.
def generate_script_from_xls(xls_name, table, cols, types):
cur.execute("delete from {}".format(table))
xl_book = xlrd.open_workbook(unicode(xls_name, "utf-8"), formatting_info=True)
sheet = xl_book.sheet_by_index(0)
dot_index = len(xls_name) - xls_name[::-1].index('.') - 1
script_name = xls_name[:dot_index] + ".txt"
comma_separated_cols = ", ".join(cols)
for rownum in xrange(1, sheet.nrows):
row = []
for colnum in xrange(sheet.ncols):
cell = sheet.cell(rownum, colnum)
if cell.value:
if types[colnum] == "float":
cell_value = cell.value
elif types[colnum] == "integer":
cell_value = int(cell.value)
else:
cell_value = u"{}".format(get_excel_visible_repr(cell, xl_book))
cell_value = u"'{}'".format(cell_value.replace("'", "\\'"))
else:
cell_value = 'NULL'
cell_value = unicode(cell_value).encode("utf-8")
row.append(cell_value)
comma_separated_data = ", ".join(row)
sql =\
"INSERT INTO {} ({}) VALUES ({});\n".format(
table,
comma_separated_cols,
comma_separated_data)
try:
cur.execute(sql)
except Exception as e:
print(e)
print(sql)
print(rownum)
con.commit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment