operation_excel.py 2.1 KB
Newer Older
“安晓东” committed
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
import os
from xmlrpc.client import boolean
import xlrd
from xlutils.copy import copy


class OperationExcel:
    def __init__(self, excel_file: str, sheet_name: str, ):
        self.excel_fiel = excel_file
        self.sheet_name = sheet_name
        self.data = self.read_excel()

    # 读取excel数据
    def read_excel(self) -> str:
        try:
            data = xlrd.open_workbook(self.excel_fiel)
            sheet = data.sheet_by_name(self.sheet_name)
            return sheet
        except FileNotFoundError as e:
            print(e)

    # 获取excel的某一行的内容
    def get_rows(self, row):
        return self.data.row_values(row)

    # 获取某一列的内容
    def get_rols(self, col):
        return self.data.col_values(col)

    # 获取excel单元格的内容
    def get_cell_data(self, row, col):
        try:
            return self.data.cell_value(row, col)
        except IndexError:
            return 0

    # excel 写入数据
    def write_excel(self, row_num: int = 0, col_num: int = 0, content: str = '') -> boolean:
        try:
            read_data = xlrd.open_workbook(self.excel_fiel)
            write_data = copy(read_data)
            sheet_data = write_data.get_sheet(self.sheet_name)
            sheet_data.write(row_num, col_num, content)
            write_data.save(self.excel_fiel)
        except FileNotFoundError as e:
            print(e)
            print(self.get_cell_data(row_num, col_num))
        if self.get_cell_data(row_num, col_num) == content:
            return True
        else:
            return False

    # 获取行数
    def get_lines(self):
        try:
            data = xlrd.open_workbook(self.excel_fiel)
            sheet = data.sheet_by_name(self.sheet_name)
            return sheet.nrows
        except FileNotFoundError as  e:
            print('没有找到文件' + str(e))


if __name__ == '__main__':
    o = OperationExcel('员工工资表.xls', 'Sheet1')
    # print(o.get_rows(2))
    print(o.get_cell_data(0, 8))
    # print(o.get_rols(2))

    # print(o.write_excel(4,4,'大家好'))
    # print(o.write_excel(4,5,'海阔天空'))
    o.get_lines()