zoukankan      html  css  js  c++  java
  • xlrd模块

    python读取Excel实例

    1、操作步骤:

    (1)安装python官方Excel库-->xlrd
    (2)获取Excel文件位置并读取
    (3)读取sheet
    (4)读取指定rows和cols内容
    python的xlrd库是第三方的,需要另外自行安装。
    利用pip命令,安装xlrd包

    2、示例代码

    # -*- coding: utf-8 -*-
    
    import xlrd
    from datetime import date,datetime
    
    def read_excel():
    
        #文件位置
        ExcelFile=xlrd.open_workbook(r'C:UsersAdministratorDesktopTestData.xlsx')
    
        #获取目标EXCEL文件sheet名
        print ExcelFile.sheet_names()
    
        #------------------------------------
        #若有多个sheet,则需要指定读取目标sheet例如读取sheet2
        #sheet2_name=ExcelFile.sheet_names()[1]
        #------------------------------------
    
        #获取sheet内容【1.根据sheet索引2.根据sheet名称】
        #sheet=ExcelFile.sheet_by_index(1)
        sheet=ExcelFile.sheet_by_name('TestCase002')
    
        #打印sheet的名称,行数,列数
        print sheet.name,sheet.nrows,sheet.ncols
    
        #获取整行或者整列的值
        rows=sheet.row_values(2)#第三行内容
        cols=sheet.col_values(1)#第二列内容
        print cols,rows
        
        #获取单元格内容
        print sheet.cell(1,0).value.encode('utf-8')
        print sheet.cell_value(1,0).encode('utf-8')
        print sheet.row(1)[0].value.encode('utf-8')
    
        #打印单元格内容格式
        print sheet.cell(1,0).ctype
    
    if __name__ =='__main__':
        read_excel()

    问题:假如我们修改其中一个值为年份,则读不出正确的日期格式,而是显示数字

    例子

    1、读取表格中第一个sheet的第一个整列的数据

    # -*- coding:utf-8 -*-
    import xlrd
    
    def read_table():
        filename = '2.xlsx'
        ip_list=[]
        rule=' '
        data=xlrd.open_workbook(filename)   #打开xlsx文件
        table=data.sheets()[0]   #文件的第一个表格
        table_name=table.name    #文件第一个表格的sheet的名字 是sheet1
        ip_list=table.col_values(0)  #获取shee1的第1个列的数据,第一列为[0],第二列为[1]
    #    ip_list=table.row_values(0)  #获取shee1的第1个行的数据
        for i in range(len(ip_list)):
            rule=rule+' or src host '+ip_list[i]
        rule=rule.strip('
    ') #读取表格时测试加不加都不会换行,没有效果,在读取txt文件时可以起到不换行的作用,不加就换行
        print(rule)
    
    if __name__=='__main__':
        read_table()

    格式化输出可以这样写:

    print('rule "(src host %s %s'%(ip_list[1],rule),')"')

     

    ---------------------------------------------------------------------------------------------
    xlrd不能操作加密的excel文件

    Unlikely to be done:
    Handling password-protected (encrypted) files.

  • 相关阅读:
    centos 卸载自带的apache
    静态方法绑定
    安装apc
    避免SSH连接因超时闲置断开
    svn使用安全问题
    接口类,和抽象类。
    function (规定参数必须为某个对象的实例)
    jquery 获取DIV边框的宽
    正则表达式(非捕获)
    Linux ftp服务器Proftp配置
  • 原文地址:https://www.cnblogs.com/dxnui119/p/10204462.html
Copyright © 2011-2022 走看看