zoukankan      html  css  js  c++  java
  • python-操作excel

    python-操作excel

    安装xlrd,xlwt

    pip install xlrd

    pip install xlwt

    栗子

    读取excel文件

    import xlrd
    
    wb = xlrd.open_workbook('user_info.xlsx')
    sheets = wb.sheets()
    #sheet = sheets[0] #获取第一个sheet
    sheet = wb.sheet_by_index(0) #获取第一个sheet
    print(sheet.nrows) #获取行数
    print(sheet.ncols) #获取列数
    print(sheet.cell_value(0, 1)) #获取指定单元格的值(第0行第1列)
    print(sheet.row_values(0)) #获取指定行数(0)的所有值
    print(sheet.row_values(0, 1, 2)) #获取指定行数的所有值,然后做切片操作

     写入excel

    #写入excel
    import xlwt
    
    wbook = xlwt.Workbook()
    wsheet = wbook.add_sheet('user1')
    wsheet.write(0, 0, 'username')
    wsheet.write(0, 1, 'password')
    wbook.save('user.xls')

    对excel操作进行封装

    opera_excel.py

    import xlrd
    
    class OperationExcel:
        """操作excel文件"""
    
        def __init__(self, file_path=None, sheet_id=None):
            if file_path:
                self.file_path = file_path
                self.sheet_id = sheet_id
            else:
                self.file_path = '../dataconfig/case1.xls'
                self.sheet_id = 0
            self.excel_sheet = self.get_excel_sheet()
    
        #获取指定excel中指定的sheet
        def get_excel_sheet(self):
            wb = xlrd.open_workbook(self.file_path)
            sheets = wb.sheets()
            return sheets[self.sheet_id]
    
        #获取excel中指定sheet的行数
        def get_sheet_lines(self):
            lines = self.excel_sheet.nrows
            return lines
    
        #获取指定sheet中一个单元格的内容
        def get_cell_value(self, row, col):
            return self.excel_sheet.cell_value(row, col)
    
    if __name__ == '__main__':
        opera_excel = OperationExcel()
        print(opera_excel.get_sheet_lines())
        print(opera_excel.get_cell_value(2, 2))
  • 相关阅读:
    MFC中添加ToolTip提示框
    神经网络算法程序
    DOS命令大全(经典收藏)
    axure团队合作开发原型图
    POJ 3233 Matrix Power Series(矩阵高速功率+二分法)
    了解你的家公家IP
    HDOJ 3518 Boring counting
    模板方法模式的房间改造-组合查询
    6最好的之一 HTML5/CSS3 演示(PPT)框架
    试想一下,在代码学习Swift!
  • 原文地址:https://www.cnblogs.com/marton/p/11020135.html
Copyright © 2011-2022 走看看