python基礎處理excel合並單元格


一、讀寫單元格數據基礎方法了解
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM