0

The code below will accept an sql file and export the data to excel using xlsxwriter but I cannot seem to get it to export with the column names as well (header). I can get it to display the column names onto the screen though, but cannot get it to add it as the first row to the excel file.

I did notice that if I change to using DictCursor instead of SSCursor, the excel file will instead be filled with just the column names repeated many times.

import MySQLdb
import sys
from xlsxwriter.workbook import Workbook
import MySQLdb.cursors as cursors

reload(sys)  
sys.setdefaultencoding('ISO-8859-1')

sql_file = sys.argv[1]
target_file = sys.argv[2]
target_sheet = sys.argv[3]

if sys.version_info[0] == 2:  # Not named on 2.6
    access = 'wb'
    kwargs = {}
else:
    access = 'wt'
    kwargs = {'newline':''}

workbook = Workbook(target_file)
worksheet = workbook.add_worksheet(target_sheet)

conn = MySQLdb.connect(host="localhost",
                     user="username",
                     passwd="password",
                     db="database"
                     , compress=1
                     )

with open(sql_file, 'r') as sql_script:
    sql_string = sql_script.read()


cur = conn.cursor(cursorclass=MySQLdb.cursors.SSCursor)
#print sql_string
cur.execute(sql_string)
results = cur.fetchall()

print ([i[0] for i in cur.description])

cur.close()
conn.close()

for r, row in enumerate(results):
    for c, col in enumerate(row):
        worksheet.write(r, c, col)

workbook.close()

1 Answer 1

2

You can get the column names and write them in the first row, then proceed with writing the row values.

cols = [i[0] for i in cur.description]
for c, col in enumerate(cols):
    worksheet.write(0, c, col)

For writing the row values:

for r, row in enumerate(results):
    for c, col in enumerate(row):
        worksheet.write(r+1, c, col)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.