So I have an SQL file with data inside of it. Which libraries do I need to import and what do I need to write in order to export that data into an Excel file?
Also extra note, I'm doing this is Python.
What do you mean 'you have a sql file'? Do you mean SQL Server? If so, try something like this.
import pyodbc
import pandas as pd
cnxn = pyodbc.connect(< db details here >)
cursor = cnxn.cursor()
script = """
SELECT * FROM my_table
"""
cursor.execute(script)
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame(list(data), columns=columns)
writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, sheet_name='bar')
writer.save()
Or, you could create your query like this.
import pyodbc
import pandas as pd
cnxn = pyodbc.connect(< db details here >)
script = """
SELECT * FROM my_table
"""
df = pd.read_sql_query(script, cnxn)
Here's one more way to connect to the data.
import pypyodbc
cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server='ServerName';"
"Database='DatabaseName';"
"Trusted_Connection=yes;")
#cursor = cnxn.cursor()
#cursor.execute("select * from Actions")
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Actions')
for row in cursor:
print('row = %r' % (row,))
I already showed you how to dump everything into Excel.