• python 2.7 操作 excel


    可以使用 openpyxl、pandas、openpyxl、xlsxwriter、xlwings、pywin32、 xlrd or xlwt 等py库 进行excel读写;

    以下通过 xlrd 和 xlwt

    pip install xlrd

    pip install xlwt

    import xlrd

    #
    1、打开文件 exceld = xlrd.open_workbook(excelpath) # 2、获取表单对象 print '表单名字:', exceld.sheet_names() print '表单数量:', exceld.nsheets print '表单对象:', exceld.sheets() print '通过名字查找:', exceld.sheet_by_name("test") print '通过索引查找:', exceld.sheet_by_index(0) data = xlrd.open_workbook(excelpath) table = data.sheet_by_index(0) for rowCount in range(table.nrows): val = (table.row_values(rowCount)) for v in val: print v

    这就完成了对excel基本数据的遍历

    API: https://xlrd.readthedocs.io/en/latest/api.html#module-xlrd

    Demo:读取 身份证号码判断年龄大于60岁 写入另一个xls

    #coding:utf-8
    import xlrd
    import xlwt
    
    excelpath = "E:\xyldy.xls"
    excel_retpath = "E:\result.xls"
    
    # 1、打开文件
    exceld = xlrd.open_workbook(excelpath)
    
    # 2、读取数据
    data = xlrd.open_workbook(excelpath)
    # 选择表单
    table = data.sheet_by_index(0)
    
    # 3、准备写结果xls 添加结果表单
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet("result")
    
    # 4、读取 身份证号码判断年龄大于60岁 写入结果
    for rowCount in range(table.nrows):
        val = (table.row_values(rowCount))
        a = val[2][6:10].encode("utf-8")
        if len(a) == 4:
            year = int(a)
            
            if (2020 - year) > 60:
                for i in range(0, len(val)):
                    sheet.write(index, i, val[i])
                index = index + 1
            else:
                print "age = " + str((2020 - year)) 
        else:
            print a
    
    # 5、保存文件
    workbook.save(excel_retpath) 
  • 相关阅读:
    娓娓道来c指针 (4)解析c的声明语句
    Snail—UI学习之UITextField
    E
    Qt录音机
    著名的英文搜索引擎
    java中Map,List与Set的差别
    Android图片处理:识别图像方向并显示
    Unity3D中组件事件函数的运行顺序
    Android屏幕density, dip等相关概念总结
    Codeforces Round #257 (Div. 2)
  • 原文地址:https://www.cnblogs.com/lesten/p/13502373.html
Copyright © 2020-2023  润新知