Last active
May 25, 2019 08:39
-
-
Save gamesbook/89af3817ff431590714706d96a5c21e7 to your computer and use it in GitHub Desktop.
Save MySQL data to an Excel file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Purpose: Import data from a MySQL database to an Excel file | |
Created: 2019-05-25 | |
Authors: Derek Hohls <[email protected]> | |
""" | |
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should really use logging rather than print functions!