zoukankan      html  css  js  c++  java
  • Python 使用 Xlrd/xlwt 操作 Excel 分类: python基础学习 2014-03-17 12:06 958人阅读 评论(0) 收藏

    Python 处理 Excel,可以使用 xlrd/xlwt 2个模块,使用简单特好上手。

    xlrd

    安装:

    sudo easy_install xlrd # windows 参考http://pypi.python.org/pypi/xlrd
    
    简单使用:

    import xlrd
    data = xlrd.open_workbook('demo.xls') # 打开demo.xls工作薄
    data.sheet_names()        # 获取xls文件中所有sheet的名称
    table = data.sheets()[0]  # 获取xls文件第一个工作表
    table = data.sheet_by_index(0)        # 通过索引获取xls文件第0个sheet
    table = data.sheet_by_name(u'Sheet1') # 通过工作表名获取 sheet
    
    #输出工作表名称
    print table.name
    # 获取行数和列数
    nrows = table.nrows
    ncols = table.ncols
    
    # 获取整行和整列的值(数组)
    table.row_values(i)
    table.col_values(i)
    
    # 循环行,得到改行的数据
    for rownum in range(table.nrows):
        print table.row_values(rownum)
    
    # 获取单元格
    cell_A1 = table.cell(0,0).value
    cell_C4 = table.cell(2,3).value
    
    # 使用行列索引获取单元格
    cell_A1 = table.row(0)[0].value
    cell_A2 = table.col(1)[0].value
    
    输出第一行单元格的值
    
    方法1:
    for i in table.row(0):
        print i.value
    
    方法2:   
    for i in sheet.row_values(0):
        print i
    
    输出数据表中的内容:
        for row in  range(table.nrows):
            for col in range(table.ncols):
                print table.cell(row,col).value,
            print
    
    # 简单的写入
    row = 0
    col = 0
    ctype = 1 # 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
    value = 'liluo'
    xf = 0 # 扩展的格式化 (默认是0)
    table.put_cell(row, col, ctype, value, xf)
    table.cell(0,0) # 文本:u'lixiaoluo'
    table.cell(0,0).value # 'lixiaoluo'
    
    输出单元格内容的方法:
    print table.row(0)[0].value
    print table.row_values(0)[0]
    print table.cell(0,0).value


  • 相关阅读:
    1136 A Delayed Palindrome (algorithm reverse(ans.begin,ans.end))
    1141 PAT Ranking of Institutions PAT甲级
    最近点对 (迭代器访问数据)
    1146 Topological Order PAT 甲级
    1151 1151 LCA in a Binary Tree PAT 甲级
    jQuery的基本使用
    案例:移动端返回顶部效果
    移动端轮播图(原生JS写法)
    移动端特效
    本地存储
  • 原文地址:https://www.cnblogs.com/think1988/p/4627920.html
Copyright © 2011-2022 走看看