【Python】WPS、Excel表格處理(一) xlrd模組
阿新 • • 發佈:2021-01-07
python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是 讀 excel,xlwt是 寫 excel的庫,這兩個適用於.xls格式有效
讀操作(xlrd模組)
xlrd模組安裝
在cmd視窗 pip install xlrd
封裝工具(函式在下面介紹)
import xlrd
import os
class ExcelTools:
# Excel讀取相關 -------------------------------------------------------------------------------
# 開啟Excel並讀取資料
@staticmethod
# 讀取表格
def readExcel(file, sheet_index=0,sheet_name='Sheet1'):
data = xlrd.open_workbook(file)#檔名以及路徑,如果路徑或者檔名有中文給前面加一個r表示原生字元
table = data.sheets()[0] # 通過索引順序獲取
# table = data.sheet_by_name(sheet_name) # 通過名稱獲取
# table = data.sheet_by_index(sheet_index) # 通過索引順序獲取
# 以上三個函式都會返回一個xlrd.sheet.Sheet()物件
# names = data.sheet_names() # 返回book中所有工作表的名字
# data.sheet_loaded(sheet_name or indx) # 檢查某個sheet是否匯入完畢
return table
# 獲取行數
@staticmethod
def get_row_count(table):
return table.nrows
# 獲取列數
@staticmethod
def get_col_count(table):
return table.ncols
# 讀取指定行
@staticmethod
def get_row_data(table, index):
return table.row_values(index)
# 讀取指定列
@staticmethod
def get_col_data(table, index):
return table.col_values(index)
# 讀取單元格資料
@staticmethod
def get_cell_data(table, row, col):
return table.cell(row, col)
匯入模組
import xlrd
開啟Excel檔案讀取資料
data = xlrd.open_workbook(file)
引數:檔名以及路徑(如果路徑或者檔名有中文給前面加一個r表示原生字元)
sheet(工作表)操作
- 通過索引順序獲取sheet
table = data.sheets()[0]
- 通過索引順序獲取sheet
table = data.sheet_by_index(sheet_indx))
- 通過名稱獲取sheet
table = data.sheet_by_name(sheet_name)
- 返回book中所有工作表的名字
names = data.sheet_names()
- 檢查某個sheet是否匯入完畢
data.sheet_loaded(sheet_name or indx)
行操作
獲取該sheet中的有效行數(屬性)
nrows = table.nrows
返回由該行中所有的單元格物件組成的列表
table.row(rowx)
返回由該行中所有的單元格物件組成的列表
table.row_slice(rowx)
返回由該行中所有單元格的資料型別組成的列表
table.row_types(rowx, start_colx=0, end_colx=None)
返回由該行中所有單元格的資料組成的列表
table.row_values(rowx, start_colx=0, end_colx=None)
返回該列的有效單元格長度
table.row_len(rowx)
列操作
獲取列表的有效列數(屬性)
ncols = table.ncols
返回由該列中所有的單元格物件組成的列表
table.col(colx, start_rowx=0, end_rowx=None)
返回由該列中所有的單元格物件組成的列表
table.col_slice(colx, start_rowx=0, end_rowx=None)
返回由該列中所有單元格的資料型別組成的列表
table.col_types(colx, start_rowx=0, end_rowx=None)
返回由該列中所有單元格的資料組成的列表
table.col_values(colx, start_rowx=0, end_rowx=None)
單元格操作
返回單元格物件
table.cell(rowx,colx)
返回單元格中的資料型別
table.cell_type(rowx,colx)
返回單元格中的資料
table.cell_value(rowx,colx)