Transfer data from MySQL or SQLite database table to create Excel worksheet by xlsxwriter library
MySQL
Here is the connection string , after successful connection we will use the variable my_conn in our examples below.
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/my_db")
usrid : Your MySql login user id pw : Your MySql login password localhost : Address of MySQL server, IP address or localhost my_db : Database name of MySQL where our table is available.
Here is the query to get 5 rows of data and all the columns from student table. Change the Query as per your requirement.
query="SELECT * FROM student LIMIT 0,5" # query
Full code to create Excel file with student table data is here
from sqlalchemy import create_engine
import xlsxwriter
my_path='G:\\My drive\\testing\\xlsxwriter\\student.xlsx' # change path
my_conn = create_engine("mysql+mysqldb://root:pw@localhost/my_tutorial")
wb = xlsxwriter.Workbook(my_path) # create workbook
ws = wb.add_worksheet() # Add worksheet
my_format = wb.add_format({'bold': True, 'font_color': 'red',
'align':'center','bg_color':'#FFFF00'}) # Header row format
query="SELECT * FROM student LIMIT 0,10" # query
my_data=my_conn.execute(query)
ws.write_row('A1',my_data.keys(),my_format) # Add header row
r,c=1,0 # row=1 and column=0
for row_data in my_data:
ws.write_row(r,c,row_data)
r=r+1 # increase row by 1 for next row
wb.close()
Using Pandas DataFrame
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/my_db")
sql="SELECT * FROM student "
df = pd.read_sql(sql,my_conn)
df.to_excel('D:\\my_data\\student.xlsx') # Change the path
Using xlsxwriter and adding different worksheets
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
sql="SELECT * FROM student WHERE class='Three'"
sql2="SELECT * FROM student WHERE class='Four'"
df=pd.read_sql(sql,my_conn) # class Three students
df2=pd.read_sql(sql2,my_conn) # class Four students
my_path='G:\\My drive\\testing\\xlsxwriter\\student2.xlsx'
with pd.ExcelWriter(my_path,engine='xlsxwriter') as my_obj:
df.to_excel(my_obj,sheet_name='Three')
df2.to_excel(my_obj,sheet_name='Four')