将Mysql数据导出到Excel工作表时,列序列正在发生变化

时间:2014-03-05 18:03:02

标签: python mysql excel

我正在尝试将Mysql表中的导出数据转换为excel表,我能够正确获取数据,但唯一的问题是,在excel表中导出该数据时,Mysql表中存在的列序列正在发生变化。我的代码是

from pyExcelerator import *
import sys
import MySQLdb
#get data from mysql
table_name = "ravi" #change the table name to the table name from which you want to create xls
sql_select="SELECT * FROM %s"%table_name
conn1 = MySQLdb.connect(host='127.0.0.1',user='root',passwd='rvrj',db='ravi') #connection information(change according to your mysql server)
cu_select=conn1.cursor(MySQLdb.cursors.DictCursor)
try:
    cu_select.execute(sql_select)
except MySQLdb.Error, e:
    sys.exit("Error message")
result_set = cu_select.fetchall()
#creation of excel file starts here
wb = Workbook()
ws0 = wb.add_sheet('0')
borders = Borders()
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
borders_cell = Borders()
borders_cell.right = 1
TestNoPat = Pattern()
TestNoPat.pattern = Pattern.SOLID_PATTERN
TestNoPat.pattern_fore_colour = 0x07
Alg = Alignment()
Alg.horz = Alignment.HORZ_CENTER
Alg.vert = Alignment.VERT_CENTER
row_number=1
for row in result_set:
    i=0
    for item in row:
        val=str(row[item])
        if (row_number==1):
            style = XFStyle()
            style.borders = borders
            style.pattern = TestNoPat
            style.alignment = Alg
            ws0.write(0,i,'', style)
            ws0.write(0,i,item, style)
            style = XFStyle()
            style.borders = borders_cell
            ws0.write(row_number,i,val, style)
            print "hi........Ravi"
            i= i+1


        else:
            style = XFStyle()
            style.borders = borders_cell
            ws0.write(row_number,i,val, style)
            print "hi......"
            i=i+1
    row_number=row_number+1
wb.save('C:\\Users\\Meenaraj\\Desktop\\%s.xls'%table_name)
print "SUCCESSFUL see in the directory a %s.xls is created "%table_name

0 个答案:

没有答案
相关问题