Skip to content

Instantly share code, notes, and snippets.

@Honghe
Created April 24, 2019 09:03
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 Honghe/5674eb53309a96485c75d4a38390fbc6 to your computer and use it in GitHub Desktop.
Save Honghe/5674eb53309a96485c75d4a38390fbc6 to your computer and use it in GitHub Desktop.
Convert Mysql database tables to Excel
# -*- coding: utf-8 -*-
import logging
import os
import mysql.connector
import pandas as pd
logging.basicConfig(level=logging.DEBUG)
def query():
output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'out')
os.makedirs(output_dir, exist_ok=True)
xlsx_filepath = os.path.join(output_dir, 'foo.xlsx')
writer = pd.ExcelWriter(xlsx_filepath)
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="1",
database="test"
)
mycursor = mydb.cursor()
mycursor.execute('show tables')
tables = mycursor.fetchall() # list
for table in tables:
table = table[0]
logging.info('table {}'.format(table))
mycursor.execute("SELECT * FROM " + table)
columns = [desc[0] for desc in mycursor.description]
myresult = mycursor.fetchall() # list
logging.info(myresult)
df = pd.DataFrame(myresult, columns=columns)
df.to_excel(writer, sheet_name=table)
writer.save()
if __name__ == '__main__':
query()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment