import xlrd3
'''
author: jxqlove?
本代码主要封装了几个操作Excel数据的方法
'''
'''
获取行视图
根据Sheet序号获取该Sheet包含的所有行,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
def getAllRowsBySheetIndex(sheetIndex, xlsFilePath):
workBook = xlrd3.open_workbook(xlsFilePath)
table = workBook.sheets()[sheetIndex]
rows = []
rowNum = table.nrows # 总共行数
rowList = table.row_values
for i in range(rowNum):
rows.append(rowList(i)) # 等价于rows.append(i, rowLists(i))
return rows
'''
获取某个Sheet的指定序号的行
sheetIndex从0开始
rowIndex从0开始
'''
def getRow(sheetIndex, rowIndex, xlsFilePath):
rows = getAllRowsBySheetIndex(sheetIndex, xlsFilePath)
return rows[rowIndex]
'''
获取列视图
根据Sheet序号获取该Sheet包含的所有列,返回值类似[ ['a', 'b', 'c'], ['1', '2', '3'] ]
sheetIndex指示sheet的索引,0表示第一个sheet,依次类推
xlsFilePath是Excel文件的相对或者绝对路径
'''
def getAllColsBySheetIndex(sheetIndex, xlsFilePath):
workBook = xlrd3.open_workbook(xlsFilePath)
table = workBook.sheets()[sheetIndex]
cols = []
colNum = table.ncols # 总共列数
colList = table.col_values
for i in range(colNum):
cols.append(colList(i))
return cols
'''
获取某个Sheet的指定序号的列
sheetIndex从0开始
colIndex从0开始
'''
def getCol(sheetIndex, colIndex, xlsFilePath):
cols = getAllColsBySheetIndex(sheetIndex, xlsFilePath)
return cols[colIndex]
'''
获取指定sheet的指定行列的单元格中的值
'''
def getCellValue(sheetIndex, rowIndex, colIndex, xlsFilePath):
workBook = xlrd3.open_workbook(xlsFilePath)
table = workBook.sheets()[sheetIndex]
return table.cell(rowIndex, colIndex).value # 或者table.row(0)[0].value或者table.col(0)[0].value
if __name__=='__main__':
rowsInFirstSheet = getAllRowsBySheetIndex(0, './产品.xls')
print(rowsInFirstSheet)
colsInFirstSheet = getAllColsBySheetIndex(0, './产品.xls')
print(colsInFirstSheet)
print(getRow(0, 0, './产品.xls'))
# 获取第一个sheet第一行的数据
print(getCol(0, 0, './产品.xls'))
# 获取第一个sheet第一列的数据
print(getCellValue(0, 3, 2, './产品.xls'))
# 获取第一个sheet第四行第二列的单元格的值
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有