按列名和 sheet 名称获取列数据
Get column data by Column name and sheet name
有没有一种方法可以使用 python xlrd 访问特定 sheet 中的列中的所有行。
例如:
workbook = xlrd.open_workbook('ESC data.xlsx', on_demand=True)
sheet = workbook.sheet['sheetname']
arrayofvalues = sheet['columnname']
还是必须自己创建字典?
excel 相当大,所以我希望避免遍历所有 colnames/sheets
此脚本允许将 xls 文件转换为字典列表,
列表中的所有字典代表一行
import xlrd
workbook = xlrd.open_workbook('esc_data.xlss')
workbook = xlrd.open_workbook('esc_data.xlsx', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # Header
for col in range(worksheet.ncols):
first_row.append( worksheet.cell_value(0,col) )
# tronsform the workbook to a list of dictionnaries
data =[]
for row in range(1, worksheet.nrows):
elm = {}
for col in range(worksheet.ncols):
elm[first_row[col]]=worksheet.cell_value(row,col)
data.append(elm)
print data
是的,您正在寻找 col_values()
工作表方法。而不是
arrayofvalues = sheet['columnname']
你需要做
arrayofvalues = sheet.col_values(columnindex)
其中 columnindex
是列的编号(从零开始计数,因此列 A 是索引 0,列 B 是索引 1,等等)。如果您在第一行(或前几行)中有一个描述性标题,您可以提供第二个参数,告诉您从哪一行开始(同样,从零开始计数)。例如,如果您有一个 header 行,因此希望值从第二行开始,您可以执行
arrayofvalues = sheet.col_values(columnindex, 1)
请查看 tutorial for a reasonably readable discussion of the xlrd
package. (The official xlrd
documentation 更难阅读。)
另请注意 (1) 虽然您可以自由使用名称 arrayofvalues
,但您真正得到的是一个 Python 列表,从技术上讲它不是数组,并且 (2 ) on_demand
工作簿参数在处理 .xlsx 文件时无效,这意味着 xlrd
无论如何都会尝试将整个工作簿加载到内存中。 (on_demand
功能适用于 .xls 文件。)
有没有一种方法可以使用 python xlrd 访问特定 sheet 中的列中的所有行。
例如:
workbook = xlrd.open_workbook('ESC data.xlsx', on_demand=True)
sheet = workbook.sheet['sheetname']
arrayofvalues = sheet['columnname']
还是必须自己创建字典?
excel 相当大,所以我希望避免遍历所有 colnames/sheets
此脚本允许将 xls 文件转换为字典列表, 列表中的所有字典代表一行
import xlrd
workbook = xlrd.open_workbook('esc_data.xlss')
workbook = xlrd.open_workbook('esc_data.xlsx', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # Header
for col in range(worksheet.ncols):
first_row.append( worksheet.cell_value(0,col) )
# tronsform the workbook to a list of dictionnaries
data =[]
for row in range(1, worksheet.nrows):
elm = {}
for col in range(worksheet.ncols):
elm[first_row[col]]=worksheet.cell_value(row,col)
data.append(elm)
print data
是的,您正在寻找 col_values()
工作表方法。而不是
arrayofvalues = sheet['columnname']
你需要做
arrayofvalues = sheet.col_values(columnindex)
其中 columnindex
是列的编号(从零开始计数,因此列 A 是索引 0,列 B 是索引 1,等等)。如果您在第一行(或前几行)中有一个描述性标题,您可以提供第二个参数,告诉您从哪一行开始(同样,从零开始计数)。例如,如果您有一个 header 行,因此希望值从第二行开始,您可以执行
arrayofvalues = sheet.col_values(columnindex, 1)
请查看 tutorial for a reasonably readable discussion of the xlrd
package. (The official xlrd
documentation 更难阅读。)
另请注意 (1) 虽然您可以自由使用名称 arrayofvalues
,但您真正得到的是一个 Python 列表,从技术上讲它不是数组,并且 (2 ) on_demand
工作簿参数在处理 .xlsx 文件时无效,这意味着 xlrd
无论如何都会尝试将整个工作簿加载到内存中。 (on_demand
功能适用于 .xls 文件。)