How to export from sql database an xlsx file with multiple sheet and exporting columns using python

我的梦境 提交于 2019-12-11 17:10:00

问题


I want to export xlsx file with multiple sheets from sql database by using queries Now I have created a three queries every query have a SELECT order for some specific data all I need now I want to export from sql database with one xlsx file but contains three sheets I new how to export data from sql database as an xlsx file but with one sheet only and this is my code

from sqlalchemy import create_engine
import pandas as pd
import os
import csv
import MySQLdb
from sqlalchemy import types, create_engine
from xlsxwriter.workbook import Workbook


# MySQL Connection
MYSQL_USER      = 'root'
MYSQL_PASSWORD  = 'xxxxxxxxxx'
MYSQL_HOST_IP   = '127.0.0.1'
MYSQL_PORT      = 3306
MYSQL_DATABASE  = 'mydb'
govtracker_table = 'govtracker' # table you want to save

con = MySQLdb.connect(user=MYSQL_USER, passwd=MYSQL_PASSWORD, 
host=MYSQL_HOST_IP, db=MYSQL_DATABASE)
cursor = con.cursor()

export_frm_db_query_ssv = "SELECT id, site_code, site_name, region, 
site_type, tac_name, dt_readiness, rfs, " \
    "rfs_date, acceptance_date_opt, acceptance_date_plan, signed_sites, " 
\
    "as_built_date, as_built_status, cluster_name, 
type_standalone_colocated, " \
    "installed_type_standalone_colocated, status, pending, pending_status, 
" \
                      "problematic_details, ets_tac, region_r, 
sf6_signed_date, " \
                      "sf6_signed_comment, comment_history, on_air_owner, 
pp_owner, " \
                      "report_comment, hu_opt_area_owner, planning_owner, 
po_number, " \
                      "trigger_date, as_built_status_tr FROM %s;" % 
govtracker_table

workbook = Workbook('SSV Progress Tracker_23 May.xlsx')
sheet = workbook.add_worksheet()
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
    sheet.write(r, c, col)
workbook.close()

the previous code is just extracting data from my database to xlsx file in one sheet only

now I have created three queries every query should be in three different sheets

#SHR Phase 1 sheet SQL query
export_frm_db_query_shr_ph1 = "SELECT id, site_code, site_name, region, 
site_type, tac_name, dt_readiness, rfs, " \
    "rfs_date, huawei_1st_submission_date, te_1st_submission_date, " \
                          "huawei_2nd_submission_date, 
te_2nd_submission_date, " \
                          "huawei_3rd_submission_date, 
te_3rd_submission_date, " \
                          "acceptance_date_opt, acceptance_date_plan, 
signed_sites, " \
    "as_built_date, as_built_status, date_dt, dt_status, " \
    "shr_status, dt_planned, integeration_status, comments_snags WHERE 
site_type = 'Existing' AND " \
                          "site_type = 'New' AND region = 'Cairo' AND 
region = 'Red sea & Sinai' " \
                          "FROM %s;" % govtracker_table

#SHR Phase 2 sheet SQL query
export_frm_db_query_shr_ph2 = "SELECT id, site_code, site_name, region, 
site_type, tac_name, dt_readiness, rfs, " \
    "rfs_date, huawei_1st_submission_date, te_1st_submission_date, " \
                          "huawei_2nd_submission_date, 
te_2nd_submission_date, " \
                          "huawei_3rd_submission_date, 
te_3rd_submission_date, " \
                          "acceptance_date_opt, acceptance_date_plan, 
signed_sites, " \
    "as_built_date, as_built_status, date_dt, dt_status, " \
    "shr_status, dt_planned, integeration_status, comments_snags WHERE 
site_type = 'Existing' AND " \
                          "site_type = 'New' AND region = 'Delta' " \
                          "FROM %s;" % govtracker_table

#SHR Phase 3 sheet SQL query
export_frm_db_query_shr_ph3 = "SELECT id, site_code, site_name, region, 
site_type, tac_name, dt_readiness, rfs, " \
    "rfs_date, huawei_1st_submission_date, te_1st_submission_date, " \
                          "huawei_2nd_submission_date, 
te_2nd_submission_date, " \
                          "huawei_3rd_submission_date, 
te_3rd_submission_date, " \
                          "acceptance_date_opt, acceptance_date_plan, 
signed_sites, " \
    "as_built_date, as_built_status, date_dt, dt_status, " \
    "shr_status, dt_planned, integeration_status, comments_snags WHERE 
site_type = 'Cow' " \
                          "site_type = 'Indoor' " \
                          "FROM %s;" % govtracker_table

now I need to export from mydatabase by this three queries in three sheets in one xlsx file that's every query in a sheet

final thing now I want to put columns in the exported xlsx file but with changing their names and just adding colors to this columns and change the text style and how to rename the sheet name instead of the default name

I hope this would be clear enough


回答1:


You can use pandas xlsxwriter, like this:

writer1 = pd.ExcelWriter('xlsx file name', engine='xlsxwriter')
your_dataframe1['column based conditions'].to_excel(writer1, sheet_name='name of sheet 1', index=False, startrow=0)
your_dataframe2['column based conditions'].to_excel(writer1, sheet_name='name of sheet 2', index=False, startrow=0)
your_dataframe3.to_excel(writer1, sheet_name='name of sheet 3', index=False, startrow=0) #no conditions here

Just make sure your data set is dataframe type. When your excel is ready type:

writer1.save()

to save it.

If you want to format dataframe header you should import:

import pandas.io.formats.excel

and type:

pandas.io.formats.excel.header_style

To format excel files you can explore openpyxl module (I don't have ready solutions) or you can import win32com.client and format sheet with VBA macro (this is pretty easy and efficent way).

Remember you need to save your writer before edit this way (writer1.save())

import win32com.client

workbook1 = xl.Workbooks.Open(Filename='file path' + 'file_name.xlsx', ReadOnly=1)
xl.Application.Run('PERSONAL.XLSB!personal macro name')
workbook1.Close(True)

To rename columns easily you can use following code:

dataframe = dataframe.rename(index=str, columns={'ID' : 'col2','CATEGORY' : 'col1','DATE' : 'col3'})

dataframe = dataframe[['col1','col2','col3']] 


来源:https://stackoverflow.com/questions/56666587/how-to-export-from-sql-database-an-xlsx-file-with-multiple-sheet-and-exporting-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!