Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Last active May 25, 2019 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamesbook/89af3817ff431590714706d96a5c21e7 to your computer and use it in GitHub Desktop.
Save gamesbook/89af3817ff431590714706d96a5c21e7 to your computer and use it in GitHub Desktop.
Save MySQL data to an Excel file
# -*- coding: utf-8 -*-
"""
Purpose: Import data from a MySQL database to an Excel file
Created: 2019-05-25
Authors: Derek Hohls <gamesbook@gmail.com>
"""
import getpass
# require pip install:
import MySQLdb
from xlsxwriter.workbook import Workbook
def write_to_excel(cursor, SQL, headers=None, filename='out.xlsx'):
query = SQL
try:
cursor.execute(query)
workbook = Workbook(filename)
sheet = workbook.add_worksheet()
top = 0
if headers:
for c, col in enumerate(headers):
sheet.write(0, c, col)
top += 1
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
sheet.write(r + top, c, col)
workbook.close()
except IOError as err:
print(err)
except Exception as err:
print(err)
return None
def connect_to_mysql(database, user='root', host='localhost'):
user = user or 'root' # your username
host = host or 'localhost' # your host
db = database or 'test' # your database
pword = getpass.getpass('"%s" database password (default:root)? ' % db)
password = pword or 'root'
try:
con = MySQLdb.connect(user=user, passwd=password, host=host, db=db)
cursor = con.cursor()
return cursor
except Exception as err:
print(err)
return None
# Example
database = 'test'
SQL = "select number, name from staff;"
headers = ['Number', 'Name', ]
cursor = connect_to_mysql(database=database)
if cursor:
write_to_excel(cursor, SQL, headers=headers, filename='staff.xlsx')
@gamesbook
Copy link
Author

Should really use logging rather than print functions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment