import pymysql,os,time,xlwt
pymysql.install_as_MySQLdb()

try:
    #创建一个excel工作簿,编码utf-8,表格中支持中文
    wb=xlwt.Workbook(encoding='utf-8')

    #创建一个sheet
    sheet=wb.add_sheet('sheet 1')


    #连接mysql
    conn = pymysql.connect(host='192.168.242.128', user='root', passwd='123456', db='cmdb', port=3306, charset='utf8')
    cur=conn.cursor()       #获取一个游标
    cur.execute('select * from Asste_aliyun;')   #执行sql
    data = cur.fetchall()  #返回执行的结果

    #获取数据的行数
    aa=int(len(data))




    #获取了数据的列数
    q=0
    for i in data[0]:
        q+=1
    print(q)



    #创建格式style
    style = xlwt.XFStyle()
    #创建font,设置字体
    font = xlwt.Font()
    # 字体格式
    font.name = 'Times New Roman'
    # 将字体font,应用到格式style
    style.font = font
    #创建alignment,居中
    alignment = xlwt.Alignment()
    # 居中
    alignment.horz = xlwt.Alignment.HORZ_CENTER
    #应用到格式style
    style.alignment = alignment



    style1 = xlwt.XFStyle()
    font1 = xlwt.Font()
    font1.name = 'Times New Roman'
    # 字体颜色(绿色)
    font1.colour_index = 3
    # 字体加粗
    font1.bold = True
    style1.font = font1
    style1.alignment = alignment
    print("2")


    ## 设置列的宽度
    for i in range(q):
        sheet.col(i).width = 5000


    list_server=["id","name","login","type","phine","account_number","password"]


    #生成头部信息
    for i in range(q):
        sheet.write(0, i, list_server[i], style1)    #0行0列

    #循环写入execl表
    for i in range(1,aa):
        for j in range(q):
            sheet.write(i,j,data[i][j],style)    #1行0列


    #保存execl
    wb.save("3.xls")



    cur.close()  # 关闭游标
    conn.close()  # 释放数据库资源


except Exception :
    print("查询失败")