{ Excel }

  • Python读写处理Excel表格常用命令及注释

    | /
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    # -*- coding: utf-8 -*-

    """

    Created on Sun Jan 21 14:13:42 2018

    @author: Hzfan

    """

    import xdrlib ,sys

    import xlrd

    #打开excel文件

    data=xlrd.open_workbook('D:\\Anaconda3\\a_py_exercise\\BlocksPy.xlsx')

    #获取第一张工作表(通过索引的方式)

    #获取工作表还有一种形式,根据sheet名字来获取excel中的sheet

    #table = data.sheet_by_name(by_name)

    table=data.sheets()[0]

    #获取行数

    nrows = table.nrows #行数

    #获取某一行数据,输入rowindex,rowindex计数从0开始

    rowvalues = table.row_values(2)

    #colvalues = table.col_values(1)

    #获取某一行数据方式二,用data_list用来存放数据

    #data_list=[]

    #将table中第一行的数据读取并添加到data_list中,对list不断的扩展

    #data_list.extend(table.row_values(0))

    list =[] #装读取结果的序列

    for rownum in range(0, nrows): #遍历每一行的内容

    row = table.row_values(rownum) #根据行号获取行

    if row: #如果行存在

    app = [] #一行的内容

    for i in range(len(rowvalues)): #一列列地读取行的内容

    app.append(row[i])

    list.append(app) #装载数据

    print ('list')

    #打印出第一行的全部数据,貌似没必要这么循环,直接用table.row_values(2)返回比较好

    #itemlist=[]

    #for item in rowvalues:

    # itemlist.append(item)

    #print ('itemlist')

    # =============================================================================

    # 以下没什么用,笔记而已

    # =============================================================================

    #使用xlwt库我们可以创建一个Excel

    # -*- coding: utf-8 -*-

    import xlwt

    def testXlwt(file = 'new.xls'):

    book = xlwt.Workbook() #创建一个Excel

    sheet1 = book.add_sheet('hello') #在其中创建一个名为hello的sheet

    sheet1.write(0,0,'cloudox') #往sheet里第一行第一列写一个数据

    sheet1.write(1,0,'ox') #往sheet里第二行第一列写一个数据

    book.save(file) #创建保存文件

    #主函数

    def main():

    testXlwt()

    if __name__=="__main__":

    main()



    #Library to create spreadsheet files compatible with MS Excel 97/2000/XP/2003

    #XLS files, on any platform, with Python 2.6, 2.6, 3.3+

    #也就是说,它只能创建 xls 的文件格式,不能创建现在的 xlsx 格式,

    #其实有点老了,如果你把文件名写了 xlsx 格式,将会无法打开。

    http://blog.csdn.net/cloudox_/article/details/53812213