【问题标题】:Dynamicaly Build Python lists from Sheets in Excel Workbook从 Excel 工作簿中的表格动态构建 Python 列表
【发布时间】:2013-08-28 22:45:22
【问题描述】:

我正在尝试压缩我之前用 python 编写的一些代码。我有一些引出的代码循环遍历 excel 工作簿中的许多查找表。工作簿中有大约 20 张包含查找表的工作表。我想遍历每个查找表中的值并将它们添加到自己的列表中。我现有的代码如下所示:

test1TableList = []
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"):
    test1TableList.append(row.Code)

test2TableList = []
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"):
    test2TableList.append(row.Code)

test3TableList = []
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"):
    test3TableList.append(row.Code)

test4TableList = []
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"):
    test4TableList.append(row.Code)

test5TableList = []
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"):
    test5TableList.append(row.Code)

呸呸呸

我想压缩该代码(可能在函数中)。

需要解决的问题:

  1. 工作表名称都不同。我需要遍历 excel 工作簿中的每个工作表,以便 a) 获取工作表对象 b) 将工作表名称用作 python 列表变量名称的一部分
  2. 我希望每个列表都保留在内存中,以便在代码中进一步使用

我一直在尝试类似的方法,但 python 列表变量似乎没有留在内存中:

import arcpy, openpyxl
from openpyxl import load_workbook, Workbook

wb = load_workbook(r"Z:\Excel\LOOKUP_TABLES.xlsx")

for i in wb.worksheets:

    filepath = r"Z:\Excel\LOOKUP_TABLES.xlsx" + "\\" + i.title + "$"
    varList = []
    with arcpy.da.SearchCursor(filepath, '*') as cursor:
        for row in cursor:
            varList.append(row[0])

    # This is the area I am struggling with. I can't seem to find a way to return 
    # each list into memory. I've tried the following code to dynamically create 
    # variable names from the name of the sheet so that each list has it's own 
    # variable. After the code has run, I'd just like to set a print statement 
    # (i.e. print variablename1) which will return the list contained in the variable
    newList = str(i.title) + "List"
    newList2 = list(varList)
    print newList + " = " + str(newList2)

我已经为此工作了一段时间,我毫不怀疑,在这一点上,我正在考虑我的解决方案,但我遇到了障碍。欢迎任何建议!

【问题讨论】:

  • 问题解决了吗?

标签: python excel list


【解决方案1】:

不确定它是否最适合您,但您可以使用 pandas 将工作表导入数据框。

from pandas.io.excel import ExcelFile
filename = 'linreg.xlsx'
xl = ExcelFile(filename)

for sheet in xl.sheet_names:
    df = xl.parse(sheet)
    print df

【讨论】:

  • 我正在使用这种确切的方法,但是当它运行到一个空工作表时代码会崩溃。有什么想法吗?
【解决方案2】:

不要使用育种列表,而是使用字典来收集每张表的数据:

import arcpy
from openpyxl import load_workbook

wb = load_workbook(r"Z:\Excel\LOOKUP_TABLES.xlsx")

sheets = {}
for i in wb.worksheets:
    filepath = r"Z:\Excel\LOOKUP_TABLES.xlsx" + "\\" + i.title + "$"
    with arcpy.da.SearchCursor(filepath, '*') as cursor:
        sheets[i.title] = [row[0] for row in cursor]

print sheets

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2021-06-10
    相关资源
    最近更新 更多