Created
November 17, 2014 11:08
-
-
Save a-milogradov/8b8b53d4f58d4033effa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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