Python operation database and excel exercise three _ general export excel

need:

As long as you pass in a table name, you can import all the data, the field name is the header of excel

1. To dynamically get the fields of the table cur.description can get the fields of the table

   fileds = [filed[0] for filed in cur.description] List generation to get the header

2. Get data select * from "%s" %table_name

3. Cyclic write to excel

   enumerate prints list subscripts and elements, loops through lists, and auto-increments subscripts to realize column auto-increment

accomplish:

def export_excel(table_name):
    import pymysql,xlwt
    host, usser, passwd, db = ' 127.0.01 ' , ' root ' , ' 123456 ' , ' data ' #Define multiple variables conn = pymysql.connect 
    (host = host,user = usser, passwd = passwd,port = 3306,db=db,charset= ' utf8 ' )
    cur = conn.cursor() #Create a cursor, specify the cursor type to return not a dictionary 
    sql = ' select * from %s; ' % table_name
    cur.execute(sql) #Execute sql 
    all_data = cur.fetchall()
    fileds = [filed[0] for filed in cur.description] #All field names, get the header 
    cur.close()
    conn.close()
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    for col,filed in enumerate(fileds):#写表头
        sheet.write(0,col,filed)
    row = 1#控制行数
    for data in all_data:#
        for col,filed in enumerate(data):#
            sheet.write(row,col,filed)
        row +=1 #Write one row each time, the number of rows +1 
    book.save( ' %s.xls ' % table_name)
export_excel('stu_info')

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325650156&siteId=291194637