前言:
1、導入xlrd模塊
2、讀取excel路徑(需要導入os)——創建workbook對象——sheet對象——獲取excel_value值
import os import xlrd excel_path =os.path.join(os.path.dirname(__file__),'data/test_data.xlsx') print(excel_path) wb =xlrd.open_workbook(excel_path) sheet =wb.sheet_by_name('Sheet1') cell_value =sheet.cell_value(1,0) # 合並的單元格,值在單元格的0,0 1,0 2,0 3,0……值為空 print(cell_value)
升級:如何將合並單元格中的所有值,取單元格左上角首個單元格的值?
解題思路:先獲取合並單元格的所在行和所在列——然后遍歷所有單元格的值,使用判斷語句來取值
merged =sheet.merged_cells #返回一個列表 起始行、結束行、起始列、結束列 [(1, 5, 0, 1)] print(sheet.merged_cells) def get_merged_cell_value(row_index,col_index): cell_value =None for (srow,erow,scol,ecol) in merged: #遍歷表格中所有合並單元格的位置信息 if (srow<=row_index and erow>row_index): # 1<=2<5 if (scol <=col_index and ecol >col_index): # 0<=0<1 #如果滿足條件,則把合並單元格首個單元格的值賦值給其他合並單元格 cell_value =sheet.cell_value(srow,scol) return cell_value print(get_merged_cell_value(3,0)) #取合並單元格的第3行第0列數據
若有以下表格數據,輸出結果:[(1, 5, 0, 1)] 爬蟲教程