【问题标题】:Python loop excel sheet printing cell valuesPython循环excel工作表打印单元格值
【发布时间】:2018-05-12 04:51:15
【问题描述】:

我正在尝试循环打印每列中的值的 excel 表。然后下到下一行,打印列的值,直到文件结束。

我的数据看起来像

Name           email                desc           date
name1          email1               desc1          date1
name2          email2               desc2          date2
name3          email3               desc3          date3



wb = load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
row_count = sheet.max_row -1
column_count = sheet.max_column
i = 1
while (i <= row_count):
 for item in sheet.iter_cols():
    #for row in sheet.iter_cols():
    first_value = item[i]
    print (first_value.value)
    i+=1

我得到错误或元组索引超出范围,而且它也没有打印正确的数据。

 first_value = item[i]
 IndexError: tuple index out of range

在我得到超出范围错误之前使用上面的代码 name1, email2, desc3 作为输出,这显然是错误的,因为数据不在同一行中

【问题讨论】:

标签: python excel


【解决方案1】:

您正在打印name1email2desc3 等值的事实表明您在列和行上都在递增。这是因为您在嵌套的 for 循环中增加了 i,而不是在外部循环中。

尝试在while循环中增加它。例如,像这样:

while (i <= row_count):
 for item in sheet.iter_cols():
   #for row in sheet.iter_cols():
   first_value = item[i]
   print (first_value.value)
 i+=1

【讨论】:

    【解决方案2】:

    解决此问题的最简单方法是将文件另存为 .csv

    然后运行:

    import csv
    with open(<YOUR_CSV_FILE_NAME>) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row)
    

    从这里您可以随意使用“行”变量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多