quisiera solicitar un ejemplo sencillo de un script en Python que lea un archivo excel y lo carge en una BD SQL Server, esto sin utilizar un controlador ODBC instalado en la máquina, puede ser con pypyodbc y pandas... algo práctico solo para orientarme del camino que debo seguir...muchas gracias.
1 respuesta
1 -> Mi concejo es: "Trata de leer la data y montarla en una query".
_PATH_EXCEL = "excel.csv" # Put file path here
_SQL_TABLE_NAME = "person"
_COL_NAMES = ['ID','Name','lastName','Age','Gender','Location'] # Put col names here
_VALUES_NAMES_FORMAT = str(_COL_NAMES).replace("[", "").replace("]", "").replace("\'", "")
_TYPES_ROWS = {'ID':int,'Name':str,'lastName':str,'Age':int,'Gender':str,'Location':str}
_DROP_HEADERS = True # if you need delete a headers of data
#Methods
def getDataInFormat(value, key_type_row):
"""
Enter a STR and return int(), str(), bool() if key_type_row
"""
# GET integer
if _TYPES_ROWS[key_type_row] == int:
return f"{value}"
if _TYPES_ROWS[key_type_row] == str:
return f"'{value}'"
if _TYPES_ROWS[key_type_row] == bool:
pass
# READ DATA
# pd.read_excel, pd.read_csv, pd.read_json... pd.read_xlsx
data = pd.read_csv(_PATH_EXCEL, sep="|", names=_COL_NAMES, encoding="utf-8")
# if delete a first row (col names)
if _DROP_HEADERS:
data = data.drop(0)
print(f"YOU READ DE FILE: {_PATH_EXCEL}\nTHE TOP#5 DATA IS\n{data.head()}")
# Create a SQL
_SQLOUTPUT = ""
print("========GENERATE SQLFILE========")
for i in range(len(data)):
_sqlValues = "" # Save here values of SQL
_d = data.iloc[i] # Save in temp file
counter_type = 0 # To macth a data with rigth type of sql insert
for key_type_row in _TYPES_ROWS:
_sqlValues = _sqlValues + getDataInFormat(_d[counter_type], key_type_row) + ","
counter_type = counter_type + 1
_sqlValues = _sqlValues[:-1] # Erase last comma
_SQLOUTPUT = _SQLOUTPUT + f"insert into {_SQL_TABLE_NAME} ({_VALUES_NAMES_FORMAT}) values ({_sqlValues});\n"
print("========PROCCES IS OVER VIEW FILE: output.sql========")
with open("output.sql", "w", encoding="UTF-8") as f:
f.write(_SQLOUTPUT)
Te dejo el link del repo:
-
1Muchas gracias Andres, me sirvió para encontrar el camino !! Commented el 20 ago. 2023 a las 21:33
-