目的:
python能使用xlrd模塊實現對Excel數據的讀取,且按照想要的輸出形式。
總體思路:
(1)要想實現對Excel數據的讀取,需要用到第三方應用,直接應用。
(2)實際操作時候和我們實際平時打開一個文件進行操作一樣,先找到文件-->打開文件-->定義要讀取的sheet-->讀取出內容。
Excel處理合并單元格:
已存在合并單元格如下:
xlrd中的 merged_cells 屬性介紹:[code]import xlrd
1
2
3
4
5
|
import xlrd workbook = xlrd.open_workbook( './data/test_data.xlsx' ) sheet = workbook.sheet_by_name( 'Sheet1' ) merged = sheet.merged_cells # 返回一個列表 起始行,結束行,起始列,結束列) print (merged) |
讀取合并單元格中的某一個單元格的值編寫成一個方法:
1
2
3
4
5
6
7
8
9
|
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 ) ) |
給出坐標,判斷是否為合并單元格:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#方法參數為單元格的坐標(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) |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/123anqier-blog/p/13234406.html