0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

To export data to a file login to sqlite shell and perform below operations

sqlite> .mode csv
sqlite> .headers on
sqlite> .output results.csv
sqlite> select * from cm_data limit 3;
sqlite> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.