zoukankan      html  css  js  c++  java
  • 操作Excel

    将数据库数据写入Excel:

    其中知识点:

    enumerate([list,list2])  #循环的时候,直接获取到下标,和值
    for index,value in enumerate([list,list2]):
    print(index,vlaue)
    fileds = ['id','name','sex','addr','gold','score']
    for index,filed in enumerate(fileds):
        print(index,filed)

    0 id
    1 name
    2 sex
    3 addr
    4 gold
    5 score

    import pymysql,xlwt
    def export_excel(table_name):
        host, user, passwd, db = 'ip, 'root', '123456', 'jxz'
        coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8')
        cur = coon.cursor()  # 建立游标,指定cursor类型返回的是字典
        sql = 'select * from %s ;'%table_name
        cur.execute(sql)  # 执行sql
        fileds = [filed[0] for filed in cur.description]  #所有的字段
        all_data = cur.fetchall()#获取所有的数据
        book = xlwt.Workbook()
        sheet  = book.add_sheet('sheet1')
        for col,filed in enumerate(fileds):   #写表头的  enumerate()循环的时候,直接获取到下标,和值
            sheet.write(0,col,filed)#写入excel
        row = 1  #行数
        for data in all_data:  #
            for col, filed in enumerate(data):  # 控制列
                sheet.write(row, col, filed)
            row+=1#每次写完一行,行就加1
        book.save('%s.xls'%table_name)
        cur.close()
        coon.close()
    export_excel('app_student')

    读取Excel数据:

    import xlrd
    book=xlrd.open_workbook('app_student.xls')
    sheet=book.sheet_by_index(0)
    #sheet=book.sheet_by_name('')
    sheet.cell(0,0)#指定Excel页里面的行和列获取数据
    # print(sheet.cell(0,0))#text:'id'
    # print(sheet.row_values(0))#这个获取到第几行的内容
    # print(sheet.row_values(1))#这个获取到第几行的内容
    # print(sheet.nrows)#获取到excel里面总共有多少行
    #for i in range(sheet.nrows):#循环获取到每行的数据
        #print(sheet.row_values(i))
    print(sheet.ncols)#总共多少列
    print(sheet.col_values(0))#获取第几列的数据

    修改Excel数据:

    import  xlutils,xlrd
    from xlutils import  copy
    book=xlrd.open_workbook('app_student.xls')
    sheet=book.sheet_by_index(0)
    #先用xlrd模块,打开一个excel
    new_book=copy.copy(book)
    #通过xlutils这个模块里面的copy方法,复制一份excel
    sheet=new_book.get_sheet(0)#获取sheet页
    list = ['编号','名字','性别','年龄','地址','班级','手机号','金币']
    
    for col,data in enumerate(list):
        #for data in list:
          sheet.write(0,col,data)
    
    #sheet.write(0,0,'编号')#第一行第一列数据修改为:编号
    #sheet.write(0,1,'名字')#第一行第二列数据修改为:名字
    new_book.save('app_student.xls')
  • 相关阅读:
    十七、Java基础之final
    十六、Java基础之super
    十五、Java基础之多态
    十四、Java基础之方法重写/覆盖
    十三、Java基础之单例模式
    十二、Java基础之继承
    十一、Java基础之static关键字
    十、Java基础之this介绍
    九、Java基础之参数传递(值传递)
    利用ResultFilter实现asp.net mvc3 页面静态化
  • 原文地址:https://www.cnblogs.com/hwtfamily/p/8999961.html
Copyright © 2011-2022 走看看