【问题标题】:How to extract data from excel in specific format & how to store in Database如何以特定格式从excel中提取数据以及如何存储在数据库中
【发布时间】:2018-10-14 07:19:14
【问题描述】:

我有下面显示的 excel 文件,我需要使用 python 提取不同格式的数据。所以请帮助我尝试以下代码:

import xlrd
book = xlrd.open_workbook("excel.xlsx")

sheet = book.sheet_by_index(0)
year=[]

# for print the year seperately in list. 
for dat in sheet.row_values(0):
     if dat is not '':
        year.append(dat)
print(year)


rowdata = []
for i in range(2, sheet.nrows):
    sheetinlist = sheet.row_values(i)
    for cell in sheetinlist:
             if cell is not '':
                rowdata.append(cell)

print(rowdata)

我用上面的代码Click to see打印了所有不带null的数据,但无法得到期望的输出
愿望输出应在列表中,如:[student age, 20, 1990], [student age, 21,1991], [student age, 22,1992],...... 整张纸。使用 for 循环。 excel表格是:click to see
所以请帮忙....等待回复...

【问题讨论】:

  • 应该在如下列表中:[student age, 20, 1990]:你的代码逻辑有问题。 student age == A3、20 == B3 和 1990 == B1。你想要rowdata[cell(A3), cell(B3), cell(B1)]、rowdata[cell(A3), cell(C3), cell(C1)] ... 为什么如果你的数据在不同列的同一行中,你会循环行吗?
  • @stvofl,是的,代码不起作用。直到现在只有我可以编码。但需要整个工作表的所需输出,因此它应该在 for 循环中意味着该逻辑适用于整个工作表
  • 您需要 edit 您的问题并将循环从 row 更改为 column。

标签: python excel database extract xlrd


【解决方案1】:

您的要求与 Excel 工作表中的数据相矛盾。我能发现的一个问题是,您现在正在清除每一行之后的列表..

    for i in range(2, sheet.nrows):
        sheetinlist = sheet.row_values(i)
        rowdata[:] = []
        for cell in sheetinlist:
                    if cell is not '':
                            rowdata.append(cell)
        print rowData

【讨论】:

  • 感谢您抽出宝贵时间,先生。但我想要 [student age, 20, 1990], [student age, 21,1991], [student age, 22,1992],......像这样的输出不想清除我可以编码的数据直到那里所以接下来我应该添加哪一个,这样我才能得到我的输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多