简体   繁体   English

使用XLRD将数据追加到列表

[英]Data append to list using XLRD

I am able to import data of rows in a particular column of certain sheet name in to a python list. 我能够将某些工作表名称的特定列中的行数据导入到python列表中。 But, the list is looking like Key:Value formatted list (not the one I need). 但是,该列表看起来像Key:Value格式的列表(不是我需要的列表)。

Here is my code: 这是我的代码:

import xlrd

excelList = []

def xcel(path):
    book = xlrd.open_workbook(path)
    impacted_files = book.sheet_by_index(2)
    for row_index in range(2, impacted_files.nrows):
        #if impacted_files.row_values(row_index) == 'LCR':
        excelList.append(impacted_files.cell(row_index, 1))
    print(excelList)

if __name__ == "__main__":
    xcel(path)

The output is like below: 输出如下:

[text:'LCR_ContractualOutflowsMaster.aspx', text:'LCR_CountryMaster.aspx', text:'LCR_CountryMasterChecker.aspx', text:'LCR_EntityMaster.aspx', text:'LCR_EntityMasterChecker.aspx', text:'LCR_EscalationMatrixMaster.aspx',....]

I want the list to have just values. 我希望列表仅包含值。 Like this... 像这样...

['LCR_ContractualOutflowsMaster.aspx', 'LCR_CountryMaster.aspx', 'LCR_CountryMasterChecker.aspx', 'LCR_EntityMaster.aspx', 'LCR_EntityMasterChecker.aspx', 'LCR_EscalationMatrixMaster.aspx',...]

I've tried pandas too ( df.value.tolist() method). 我也尝试过熊猫( df.value.tolist()方法)。 Yet the output is not what I visualize. 但是输出不是我想象的。

Please suggest a way. 请提出一种方法。

Regards 问候

You are accumulating a list of cells, and what you are seeing is the repr of each cell in your list. 您正在累积一个单元格列表,并且看到的是列表中每个单元格的repr Cell objects have three attributes: ctype is an int that identifies the type of the cell's value, value (which which is a Python rtype holding the cell's value) and xf_index. 单元格对象具有三个属性: ctype是一个int,用于标识单元格值的类型, valuevalue (这是保存单元格值的Python rtype))和xf_index。 If you want only the values then try 如果只需要这些值,请尝试

excelList.append(impacted_files.cell(row_index, 1).value)

You can read more about cells in the documentation . 您可以在文档中阅读有关单元的更多信息。

If you are willing to try one more library, openpyxl this is how it can be done. 如果您愿意尝试一个更多的库, openpyxl这是可以做到的。

from openpyxl import load_workbook
book = load_workbook(path)
sh = book.worksheets[0]
print([cell.value for cell in row for row in sheet.iter_rows()] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM