一、读写单元格数据基础方法了解
work_book = xlrd3.open_workbook("test_data.xls",formatting_info=True) #读取excel文件,创建工作薄对象
sheet = work_book.sheet_by_name("Sheet1") # 根据sheet名创建对应的表格对象
cell_value = sheet.cell_value(0,1) #获取单元格的值
tuper = sheet.merged_cells #获取sheet中所有的合并单元格
nrowls = sheet.nrows 获取行数
ncols = sheet.ncols 获取列数
将处理单元格进行二次封装
1-)定义一个类:
class ExcelUtils:
def __init__(self,excel_file_path,sheet_name):
self.excel_file_path = excel_file_path
self.sheet_name = sheet_name
# self.work_book = xlrd3.open_workbook(self.excel_file_path, formatting_info=True)
self.work_book = xlrd3.open_workbook(self.excel_file_path)
# self.sheet = self.get_sheet()
self.sheet = self.work_book.sheet_by_name(self.sheet_name)
2-)处理合并单元格,让合并单元格中每一个格子取出左上角的值
def get_merged_cell_value(self,row_value, col_value):
for (min_row_index, max_row_index, min_col_index, max_col_index) in self.sheet.merged_cells:
if row_value >= min_row_index and row_value < max_row_index:
if col_value >= min_col_index and col_value < max_col_index:
cell_value = self.sheet.cell_value(min_row_index, min_col_index)
break #防止在第一次循环完成取出值后,再次循环判断,覆盖原本的值
else:
cell_value = self.sheet.cell_value(row_value, col_value)
else:
cell_value = self.sheet.cell_value(row_value, col_value)
return cell_value