Create a SQLite import script with Python
Quote identifiers and values, then write a reviewable SQL script without contacting a database.
View code and setup
Before you start
- Install Python 3. Create the environment below, save the Python example as task.py, then run .venv/bin/python task.py in the folder containing input.xlsx. On Windows, use py -m venv .venv and .venv\Scripts\python.exe in place of .venv/bin/python. Replace Inventory with your worksheet name.
python3 -m venv .venv
.venv/bin/python -m pip install openpyxlfrom openpyxl import load_workbook
workbook = load_workbook("input.xlsx", read_only=True, data_only=True)
sheet = workbook["Inventory"]
rows = sheet.iter_rows(values_only=True)
headers = list(next(rows))
if any(not isinstance(key, str) or not key.strip() for key in headers):
raise ValueError("Use nonblank text headers in the first row")
if len(set(headers)) != len(headers):
raise ValueError("Use unique headers")
records = [dict(zip(headers, row)) for row in rows]
workbook.close()
def identifier(text):
return '"' + text.replace('"', '""') + '"'
def literal(value):
return "NULL" if value is None else "'" + str(value).replace("'", "''") + "'"
columns = ", ".join(identifier(name) + " TEXT" for name in headers)
statements = [f'CREATE TABLE "inventory" ({columns});']
for record in records:
values = ", ".join(literal(record[name]) for name in headers)
statements.append(f'INSERT INTO "inventory" VALUES ({values});')
with open("output.sql", "w", encoding="utf-8") as output:
output.write("\n".join(statements) + "\n").venv/bin/python task.pyLimits and output
- These data recipes use saved cell results, not recalculated formulas. They do not copy charts, styles, macros or workbook relationships. Keep the original file.
- The script targets SQLite and deliberately stores non-null values as TEXT. It creates a new inventory table and fails if it exists. Review before execution; do not apply it to a production database as a test.
Documentation: openpyxl tutorial and workbook loading options