python 操作excel
#!/usr/bin/python # -*- coding:utf-8 -*- import xlrd import xlwt class ExcelRead: # Manage Excel Read current_sheet = None def __init__(self, excel_file_path): self.excel_file_path = excel_file_path # open Excel def open(self): try: self.file_read_open = xlrd.open_workbook(self.excel_file_path) except Exception as e: print("Cann't Open Excel:", e) # get All Sheets def get_all_sheets(self): return self.file_read_open.sheets() # get Sheets Num def get_sheets_num(self): return len(self.file_read_open.sheet_names()) # get Sheet def get_sheet(self, key): if isinstance(key, str): # by sheet name workSheet = self.file_read_open.sheet_by_name(key) else: # by sheet index workSheet = self.file_read_open.sheet_by_index(key) return workSheet # ============================================== # get Sheet rows cols def get_sheet_row_and_col_len(self, key): tem_sheet = self.get_sheet(key) return (tem_sheet.nrows, tem_sheet.ncols) def get_current_sheet_row_and_col_len(self): return (self.current_sheet.nrows, self.current_sheet.ncols) def get_sheet_nrows(self, key): return self.get_sheet(key).nrows def get_current_sheet_nrows(self): return self.current_sheet.nrows def get_sheet_ncols(self, key): return self.get_sheet(key).ncols def get_current_sheet_ncols(self): return self.current_sheet.ncols # get Sheet Value def get_cell_value(self, row, col, key): return self.get_sheet(key).cell_value(row, col) def get_current_cell_value(self, row, col): return self.current_sheet.cell_value(row, col) # set Current Sheet def set_current_sheet(self, key): self.current_sheet = self.get_sheet(key) # init Row Index def init_row_index(self, index=0): self.row_index = index # next Row def next_row(self): ret = self.current_sheet.row_values(self.row_index) self.row_index += 1 return ret # is Row Done def is_row_continue(self): if self.row_index < self.get_current_sheet_nrows(): return 0 else: return 1 def get_all_value(self): all_value_list = [] row_and_col = self.get_current_sheet_row_and_col_len() for row in range(row_and_col[0]): row_list = [] for col in range(row_and_col[1]): val = self.get_current_cell_value(row, col) row_list.append(val) all_value_list.append(row_list) return all_value_list class ExcelWrite: work_sheet = None def __init__(self, excel_file_path): self.excel_file_path = excel_file_path def open(self): try: workbook = xlwt.Workbook(encoding='utf-8') self.work_sheet = workbook.add_sheet(self.excel_file_path) except Exception as e: print("Cann't Open Excel:", e) def write_value(self, row, col, value): self.work_sheet.write(row, col, label=value) def save(self): self.work_sheet.save('new_excel_file')