在python 中操作excel表格,读取excel 模块常使用的是 xlrd,写excel 模块使用的是xlwt
#读取excel 表
import xlrd
#打开excel
myWorkbook = xlrd.open_workbook(‘example.xls‘)
#获取sheet 页内容
mySheets = myWorkbook.sheets()
#打印sheets 页
print(mySheets,type(mySheets))
执行后结果
[<xlrd.sheet.Sheet object at 0x0000000001463940>, <xlrd.sheet.Sheet object at 0x00000000014639E8>, <xlrd.sheet.Sheet object at 0x0000000001463A20>] <class ‘list‘>
mySheet1 = myWorkbook.sheet_by_index(0) # 根据索引获取sheet 页内容
print(mySheet1)
mySheet2 = myWorkbook.sheet_by_name(u‘分组‘)
print(mySheet2)
执行后结果
<xlrd.sheet.Sheet object at 0x00000000014B3978>
<xlrd.sheet.Sheet object at 0x00000000014B3978>
#获取行数
#mySheet1 表的行数
mySheet1 = myWorkbook.sheet_by_index(0)
MRows = mySheet1.nrows
MCows = mySheet1.ncols
mySheet1 = myWorkbook.sheet_by_index(0)
MRows = mySheet1.nrows
MCows = mySheet1.ncols
print(MRows, MCows)
#执行后结果展示
18 1 #18 行,1列
#获取行的内容
mySheet1 = myWorkbook.sheet_by_index(0)
MRows_value = mySheet1.row_values(0) # 获取行的内容
MCows_value = mySheet1.col_values(0) # 获取列的内容
print(MRows_value, MCows_value)
#执行后结果展示
[‘组名‘] [‘组名‘, ‘FILE_UPLOAD_CONFIG‘, ‘TRACE_LOG_CONFIG‘, ‘TRACE_LOG_KAFKA_CONFIG‘, ‘a_howbuy‘, ‘activity-config‘, ‘auth-center‘, ‘cgi-simu‘, ‘cms‘, ‘cmsactivity‘, ‘cmsfund‘, ‘common‘, ‘config‘, ‘content‘, ‘coop-merchant‘, ‘coop-tenpay‘, ‘coop-trade‘, ‘coop-trade-apistd‘]
#获取单元格的内容,主要有两种方式
方式一、
my_cell_value = mySheet1.cell(0, 0) # 第一个参数是行,第二个参数是列
print(my_cell_value.value)
#执行后展示
组名
方式二、
my_cell_value3 = mySheet1.cell_value(9,0) # 第一个参数是行,第二个参数是列
print(my_cell_value3)
#执行后展示
cmsactivity
#循环遍历单元格的内容
len_rows = mySheet1.nrows #行数
for i in range(len_rows):
print(mySheet1.cell_value(i, 0))
#执行后展示
FILE_UPLOAD_CONFIG
TRACE_LOG_CONFIG
TRACE_LOG_KAFKA_CONFIG
a_howbuy
activity-config
auth-center
cgi-simu
cms
cmsactivity
cmsfund
common
config
content
coop-merchant
coop-tenpay
coop-trade
coop-trade-apistd
原文地址:https://blog.51cto.com/sdsca/2365567