Python中openpyxl模块的使用
class ExcelManual:
def __init__(self, file_path):
self.file_path = file_path
self.wb = load_workbook(file_path)
self.live_sheet = None
def select_sheet(self, name):
"""
选择表单
:param name: 表单名称
:return:
"""
self.live_sheet = self.wb[name]
return self.live_sheet
def read_cell_value(self, row, column):
"""
读取一个单元格的数据内容
:param row: 行
:param column: 列
:return:
"""
if isinstance(self.live_sheet, Worksheet):
return self.live_sheet.cell(row, column).value
def write_value_in_cell(self, row, column, value):
"""
往单元格中写入数据
:param row:行
:param column:列
:param value:值
:return:
"""
self.live_sheet.cell(row, column, value)
def read_row_value(self, row_num):
"""
读取一行的数据功能
:return:
"""
if isinstance(self.live_sheet, Worksheet):
max_row = self.live_sheet.max_row
if row_num > max_row:
print("行数超过表单中的最大行数")
return
max_column = self.live_sheet.max_column
data_list = []
for i in range(max_column):
data_list.append(self.live_sheet.cell(row_num, i + 1).value)
return data_list
def read_value_by_sheet(self, sheet_name):
"""
获取表单中的所有数据
:param sheet_name:
:return:
"""
current_sheet = self.wb[sheet_name]
if isinstance(current_sheet, Worksheet):
return list(current_sheet.values)
def close(self):
"""操作完一定要保存关闭才有效"""
self.wb.save(self.file_path)
self.wb.close()