我一直在用python编写一个函数,使用openpyxl
库,它将从工作簿中的指定工作表加载列,并在返回列表或numpy数组中的列之前进行一些数据调整。在
要加载列,我要加载工作簿,获取目标工作表,存储列,然后简单地遍历每个列并将单元格内容附加到列表中:
#open the excel file
wb = openpyxl.load_workbook(fname, read_only = True)
print('\nWorkbook "%s" open...' % (fname))
#get the target sheet
sh = wb.get_sheet_by_name(sheet)
print('Sheet "%s" aquired...' % (sheet))
#store only the desired columns of the sheet
sheetcols = sh.columns
columns = [[] for i in range(L)]
for i in range(L):
columns[i] = sheetcols[cols[i] - 1]
#read selected columns into a list of lists
print('Parsing desired columns of data...')
data = [[] for i in range(L)]
#iterate over the columns
for i in range(L):
#iterate over a specific column
print(len(columns[i]))
for j in range(len(columns[i])):
#store cell contents as a string (for now)
data[i].append(columns[i][j].value)
某些列将在其各自列表的开头加载多个与excel文件中的数据不对应的None
元素。例如,一个在开头有两个空单元格的列(由于标题空间或其他原因而保留为空)应该在其列表的开头加载两个None
元素,但它可能会加载五个或六个None
元素,而不是两个。。。在
每次我运行函数都是一致的。同样的列每次都会有这个问题,这让我觉得excel表中有某种类型的隐藏数据。我试着清除那些应该是空的但没有运气的细胞。在
有没有更熟悉openpyxl
模块或者仅仅是excel的人有没有想过为什么这些神秘的额外的None
元素会进入导入的数据中?在
代码不完整,但可能值得注意的是,缺少单元格的工作表的行为必然有些不可预测。例如,如果工作表的单元格中只有
D3:G8
中的值,那么它的列应该是什么?openpyxl将按需为任何给定范围创建单元,我想这就是您可能看到的。在ws.rows
和{相关问题 更多 >
编程相关推荐