python excel如何提取想要的列
1、首先安装xlrd:
pip3 install xlrd
然后上代码:
import numpy as np
import xlrd
data = xlrd.open_workbook('LifeTable_16.xlsx')
table = data.sheets()[0]
# print(table)
# nrows = table.nrows #行数
# ncols = table.ncols #列数
# c1=arange(0,nrows,1)
# print(c1)
start=6 #开始的行
end=106 #结束的行
rows=end-start
list_values=[]
for x in range(start,end):
values=[]
row =table.row_values(x)
for i in range(1,7):
# print(value)
values.append(row[i])
list_values.append(values)
# print(list_values)
datamatrix=np.array(list_values)
print(datamatrix)
以上这篇python3读取excel文件只提取某些行某些列的值方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
2、Python对Excel的读写主要有xlrd、xlwt、xlutils、openpyxl、xlsxwriter几种。1、xlrd主要用来读取Excel文件(Excel read)import xlrdworksheet = xlrd.open_workbook(u'Python操作Excel.xls')sheet_names= worksheet.sheet_names()for sheet_name in sheet_names:sheet2 = worksheet.sheet_by_name(sheet_name)print sheet_name rows = sheet2.row_values(3) # 获取第四行内容cols = sheet2.col_values(1) # 获取第二列内容print rowsprint cols
3、一直想将自己接触到的东西梳理一遍,可就是迈不出第一步,希望从这篇总结开始不要再做行动的矮人了。
最近测试过程中需要用到python读取excel用例数据,于是去了解和学习了下xlrd库,这里只记录使用过程中读取excel数据相关操作。
一、安装xlrd库
可以下载xlrd库包到本地安装,也可以通过pip命令安装,这里我选择pip命令:
pip install xlrd
二、使用xlrd读取excel数据
具体详细的操作可以参考xlrd库操作说明文档,以下是两种读取excel数据的方法:
1、根据Excel中sheet名称读取数据:
1def readExcelDataByName(fileName, sheetName):
2 table = None
3 errorMsg = None
4 try:
5 data = xlrd.open_workbook(fileName)
6 table = data.sheet_by_name(sheetName)
7 except Exception, msg:
8 errorMsg = msg 9 return table, errorMsg
4、2、根据Excel中sheet的序号获取:
1 def readExcelDataByIndex(fileName, sheetIndex):
2 table = None
3 errorMsg = ""
4 try:
5 data = xlrd.open_workbook(fileName)
6 table = data.sheet_by_index(sheetIndex)
7 except Exception, msg:
8 errorMsg = msg
9 return table, errorMsg
5、3、根据列名获取相应序号,由于有时读取excel中列数据时,需要通过列头名称获取相应的列中的值,所以写了下面这个返回列名所在表格中的index。然后就可以直接通过table.cell_value(i, getColumnIndex(table,'列名'))获取列的值。
1 def getColumnIndex(table, columnName):
2 columnIndex = None 3
3 for i in range(table.ncols): 5
4 if(table.cell_value(0, i) == columnName):
5 columnIndex = i
6 break
7 return columnIndex