Created
January 29, 2021 19:55
-
-
Save viperscape/cc6932105a9ae809e3bacc1f0f6e0a2c to your computer and use it in GitHub Desktop.
creates a dbo schema based on a spreadsheet's tables
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
import openpyxl as xl | |
def get_table(workbook, sheet_name, table_name): | |
ws = workbook[sheet_name] | |
g = workbook.defined_names[table_name].destinations | |
# note we expect python 3.7 ordered dictionaries by default | |
table = {} | |
for s,a in g: | |
for col in ws[a][0]: # get columns | |
table[col.value.replace(' ','_')] = { "data": [], "is_date": False } | |
# zip the data into the table | |
for n in ws[a][1:]: # get data in range | |
for i,k in enumerate(table): | |
table[k]["data"].append(n[i].value) | |
if (n[i].is_date): # find any dates, whole column is a date type | |
table[k]["is_date"] = True | |
table["_name"] = table_name | |
return table | |
def get_item_value(table, column_name, origin_name, item_name): | |
return table[column_name][table[origin_name].index(item_name)] | |
# must be data_only to get cached values | |
def get_workbook(xl_file): | |
wb = xl.load_workbook(xl_file, data_only=True, read_only=True) | |
return wb | |
# generate sql schema | |
def get_schema(table): | |
name = table["_name"] | |
schema = f"CREATE TABLE dbo.{name} (\n" | |
for i,col in enumerate(table.items()): | |
if (i < 1): | |
schema += f"{col[i]} TEXT NOT NULL" | |
continue | |
if (i == len(table) - 1): | |
continue | |
schema += ",\n" | |
schema += f"{col[0]} " | |
schema += "DATE" if col[1]["is_date"] else "FLOAT" | |
schema += "\n);" | |
return schema |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment