目的:
python能使用xlrd模塊實現對Excel數據的讀取,且按照想要的輸出形式。
總體思路:
(1)要想實現對Excel數據的讀取,需要用到第三方應用,直接應用。
(2)實際操作時候和我們實際平時打開一個文件進行操作一樣,先找到文件-->打開文件-->定義要讀取的sheet-->讀取出內容。
Excel處理合並單元格:
已存在合並單元格如下:
xlrd中的 merged_cells 屬性介紹:
import xlrd
workbook = xlrd.open_workbook('./data/test_data.xlsx')
sheet = workbook.sheet_by_name('Sheet1')
merged = sheet.merged_cells # 返回一個列表 起始行,結束行,起始列,結束列)
print(merged)
讀取合並單元格中的某一個單元格的值編寫成一個方法:
def get_merged_cell_value(row_index,col_index):
cell_value = None
for (rlow, rhigh, clow, chigh) in merged:
if (row_index >= rlow and row_index < rhigh):
if (col_index >= clow and col_index < chigh):
cell_value = sheet.cell_value(rlow, clow)
return cell_value
print( get_merged_cell_value(0,1) )
給出坐標,判斷是否為合並單元格:
#方法參數為單元格的坐標(x,y),如果給的坐標是合並的單元格,輸出此單元格是合並的,否則,輸出普通單元格
def get_merged_cell_value(row_index,col_index):
for (rlow, rhigh, clow, chigh) in merged:
if (row_index >= rlow and row_index < rhigh and col_index >= clow and col_index < chigh):
print("此單元格是合並單元格")
else:
print("此單元格為普通單元格")
print( get_merged_cell_value(4,3) )
##讀取第3列的所有數據,並進行降序排序
clox=3
list1=[]
for i in range(1,sheet.nrows):
cell_value=float(sheet.cell_value(i,clox))
list1.append(cell_value)
print(list1)
list1.sort()
list1.reverse()
print(list1)