使用OpenPyXL在Python中将Excel数据写入字典时的错误

2024-10-01 17:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉用一堆深奥的代码打你,但是我遇到了一个我不知道如何修复的bug。在

基本上,我希望读取电子表格列中的单个单元格,并将其数据写入相应的字典(称为数据集)。在

我创建了一个函数来执行此操作:

def loopCol(col, start_offset, write_list):
'''
Loop through 1 column (col) until it ends. Skip header by start_offset.
Write data to list within DataSet dict
'''
from openpyxl.utils import column_index_from_string

# Create list and capture str of its name
list_string = str(write_list)
print(list_string)
if list_string not in dataSet:
    raise KeyError('List name not within DataSet Keys')
write_list = []

# Loop through column, capturing each cell's value
# Use start_offset to skip header cells
for i in range(column_index_from_string(col) + start_offset,
               sheet.max_row + 1):
    listItem = sheet[col + str(i)].value
    print(listItem)
    if listItem != None:
        if isinstance(listItem, datetime.datetime):
            listItem = listItem.strftime('%d/%m/%Y')
            write_list.append(listItem)
        else:               
            write_list.append(listItem)

# Write data to dataSet
for list_index in write_list:
    dataSet[list_string] = [list_index for list_index in write_list]

loopCol('A', 0, 'dates')
loopCol('B', 0, 'ph')
loopCol('C', 0, 'water_level')
loopCol('D', 0, 'salinity')
loopCol('E', 1, 'conductivity')
loopCol('F', 0, 'tds')

所以理论上讲,这应该遍历一列中的所有单元格,如果其中有值,请将该值写到字典中相应的位置:

^{pr2}$

但是,有一个问题。说到做到,字典看起来像:

{'ph': [3.4, 2.1, 7], 'salinity': [2.2, 1.2], 'conductivity': [5.3], 'water_level': ['2m', '3m', '1m'], 'tds': [], 'dates': ['Date', '21/01/2016', '28/01/2012', '06/03/2012']}

我现在知道每列有3个值。不过,有些人还没有被列入词典“盐度”只有2个值,“电导率”只有1个,“tds”为空。这些数据恰好是数据集dict中的最后一个条目,所以这可能是部分原因。但我就是不知道逻辑中的错误在哪里。在

Here's a screen of the file for context

有人能帮忙吗?我真的很想给我的老板留下深刻的印象(我不从事IT工作,所以任何能让人们生活更轻松的电脑奇才都会受到惊奇和敬畏)。在

如果我没有很好地解释代码到底在做什么,请让我知道,我会尽力澄清。在


Tags: to数据infromstringindex字典column
1条回答
网友
1楼 · 发布于 2024-10-01 17:27:26

你可以试试这样的方法:

def colValues(sheet, keys, offsets=None):
    if offsets is None or not len(offsets):
        # Set offsets default to 0
        offsets = {k: 0 for k in keys}
    if len(offsets) != len(keys):
        # If offsets given, fail if length mismatch
        raise AttributeError()

    res = {}
    for column in sheet.columns:
        # Store current column header field (i.e. its name)
        ch = column[0].value
        if ch not in keys:
            # Fail early: No need for any tests if this column's data
            # is not desired in result set.
            continue
        # Append all row values to the result dict with respect to the
        # given column offset. Note: Lowest possible row index is 1,
        # because here we assume that header fields are present.
        res[ch] = [c.value for c in column[offsets[keys.index(ch)] + 1:]]
    return res

if __name__ == '__main__':
    xlsx = 'test.xlsx'
    ws = load_workbook(xlsx)['Sheet1']

    ds = colValues(ws, ['foo', 'bar'], [0, 1])
    print(ds)

对于我的测试,每列正确的小项目数。注意,键'bar'在这里少了一个项,因为在上面的函数调用中,它的偏移量更大。在

^{pr2}$

此外,代码更轻。在

相关问题 更多 >

    热门问题