使用 XLRD 将数据附加到列表

Data append to list using XLRD

我能够将某些 sheet 名称的特定列中的行数据导入到 python 列表中。但是,该列表看起来像 Key:Value 格式的列表(不是我需要的)。

这是我的代码:

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)

输出如下:

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

我希望列表只有值。像这样...

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

我也试过 pandas(df.value.tolist() 方法)。然而,输出并不是我想象的那样。

请推荐一个方法。

此致

如果您愿意再尝试一个库,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()] )

您正在累积一个单元格列表,您看到的是列表中每个单元格的 repr。单元格对象具有三个属性:ctype 是一个标识单元格值类型的整数,value(这是一个 Python 保存单元格值的 rtype)和 xf_index .如果您只想要值,请尝试

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

您可以在 documentation 中阅读有关单元格的更多信息。