zoukankan      html  css  js  c++  java
  • python-xlrd,xlwt excel文件的读写

    xlrd,xlwt excel文件的读写

    话不多说,直接上代码,然后解释

    import xlwtimport xlrd
    import numpy as np
    path="C:/learn_data/"
    #Excel数据
    #生成xls工作薄
    wb = xlwt.Workbook()
    print(wb) 
    wb.add_sheet('first_sheet', cell_overwrite_ok=True) 
    wb.get_active_sheet() 
    ws_1 = wb.get_sheet(0) 
    print(ws_1) 
    ws_2 = wb.add_sheet('second_sheet')
    data = np.arange(1, 65).reshape((8, 8))
    print(data) ws_1.write(0, 0, 100) 
    for c in range(data.shape[0]):    
        for r in range(data.shape[1]):        
             ws_1.write(r, c, int(data[c, r]))        
             ws_2.write(r, c, int(data[r, c]))
    wb.save(path + 'workbook.xls') 
    #生成xlsx工作薄 
    #从工作薄中读取
    book = xlrd.open_workbook(path + 'workbook.xls')
    print(book) 
    print(book.sheet_names())
    sheet_1 = book.sheet_by_name('first_sheet')
    sheet_2 = book.sheet_by_index(1)
    print(sheet_1)
    print(sheet_2.name) 
    print(sheet_1.ncols, sheet_1.nrows) cl = sheet_1.cell(0, 0)print(cl.value) 
    print(cl.ctype) 
    print(sheet_2.row(3))
    print(sheet_2.col(3)) 
    print(sheet_1.col_values(3, start_rowx=3, end_rowx=7)) print(sheet_1.row_values(3, start_colx=3, end_colx=7)) 
    for c in range(sheet_1.ncols):    
        for r in range(sheet_1.nrows):        
            print ('%i' % sheet_1.cell(r, c).value,)    
        print

    上述代码
    wb = xlwt.Workbook()就是创建了一个工作簿对象,然后我们就可以在工作簿中添加工作表
    wb.add_sheet(‘first_sheet’, cell_overwrite_ok=True)

    cell_overwrite_ok=True)表示可以对表进行写操作

    wb.get_active_sheet() 表示获得当前活动表

    ws_1 = wb.get_sheet(0) 按序号获得表,0表示第一个

    ws_2 = wb.add_sheet(‘second_sheet’)可以直接创建一个表并赋值给一个对象,然后直接进行操作

    ws_1.write(r, c, int(data[c, r])) 对第r行,第c列进行写入操作

    wb.save(path + ‘workbook.xls’) 保存工作簿

    book = xlrd.open_workbook(path + ‘workbook.xls’)
    #打开一个工作簿

    book.sheet_names() #返回工作簿的表名
    sheet_1 = book.sheet_by_name(‘first_sheet’) 通过工作表名称获得表
    sheet_2 = book.sheet_by_index(1) 通过索引获得表

    sheet_1.cell(r, c).value 返回第r行第c列的值
    print(sheet_2.row(3)) 输出第四行
    print(sheet_2.col(3)) 输出第四列

  • 相关阅读:
    MySQL——索引
    MySQL——逻辑分层与存储引擎
    APP测试总结
    如何提高测试的质量
    测试用例的基础
    opencv图像处理常用操作一
    【bug】【Cannot find reference 'imread' in '__init__.py | __init__.py'】
    Numpy学习笔记
    工业互联网
    Python基本的数据清洗
  • 原文地址:https://www.cnblogs.com/gaoxing2580/p/13193453.html
Copyright © 2011-2022 走看看