簡體   English   中英

使用XLRD將數據追加到列表

[英]Data append to list using XLRD

我能夠將某些工作表名稱的特定列中的行數據導入到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',...]

我也嘗試過熊貓( df.value.tolist()方法)。 但是輸出不是我想象的。

請提出一種方法。

問候

您正在累積一個單元格列表,並且看到的是列表中每個單元格的repr 單元格對象具有三個屬性: ctype是一個int,用於標識單元格值的類型, valuevalue (這是保存單元格值的Python rtype))和xf_index。 如果只需要這些值,請嘗試

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

您可以在文檔中閱讀有關單元的更多信息。

如果您願意嘗試一個更多的庫, 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