Operating excel spreadsheet

import xlrd
from xlutils.copy import copy


class OpraterExcel():
def __init__(self, file_path=None, sheet_index=None):
if file_path == None:
self.file_path = '../configdata/test.xlsx'
else:
self.file_path = file_path

if sheet_index == None:
self.sheet_index = 0
else:
self.sheet_index = sheet_index
self.sheet = self.load_file()

def load_file(self):
workbook = xlrd.open_workbook(self.file_path)
sheet = workbook.sheet_by_index(self.sheet_index)
return sheet

def get_value(self,row,col):
'''
依据行列获取表格数据
:param row:
:param col:
:return:
'''
return self.sheet.cell_value(rowx=row,colx=col)

def write(self, row, col, data):
'''
写入数据
:param row:
:param col:
:param data:
:return:
'''
book = xlrd.open_workbook(self.file_path)
copy_book = copy(book)
sheet_data = copy_book.get_sheet(0)
sheet_data.write(row,col,data)
copy_book.save(self.file_path)


def get_lines(self):
'''
获取sheet表格行数
:return:
'''
return self.sheet.nrows


if __name__ == '__main__':
oe = OpraterExcel()
n = oe.get_lines()
print('行数:%s' %(n))
sheet = oe.sheet
cols = sheet.col_values(0)
print(cols)
# book = xlrd.open_workbook('../configdata/test.xlsx')
# sheet = book.sheet_by_index(0)
# row_num = sheet.nrows
# col_num = sheet.ncols
# d = sheet.cell(0, 0).value
# f = sheet.cell_value(1, 1)
# a = sheet.row_values(0)
# b = sheet.col_values(0)
# print(len(a))
# print(a[0])
#
# for i in range(0, len(a)):
# print(a[i])

Guess you like

Origin www.cnblogs.com/xinyueqingfeng/p/11725887.html