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))
  • 相关阅读:
    ios10 获取idfa的坑
    iOS 获取手机sim卡的运营商(移动,电信,联通) 相关信息
    iOS获取手机IP地址
    UIScrollView 与 touchesBegan 冲突解决方法
    32位与64位基础
    MySQL数据库基础_表&简单查询
    MySQL数据库基础
    Java_File、递归
    Java_lambda表达式
    Java线程锁,等待唤醒和线程池
  • 原文地址:https://www.cnblogs.com/marton/p/11020135.html
Copyright © 2011-2022 走看看