簡體   English   中英

使用OpenPyXL在Excel中將Excel數據寫入Dictionary的錯誤

[英]Bug in writing Excel data to Dictionary in Python with OpenPyXL

很抱歉用一堆深奧的代碼打了你,但我遇到了一個不知道如何解決的錯誤。

基本上,我想讀取電子表格列中的單個單元格並將其數據寫入相應的字典(稱為dataSet)。

我創建了一個函數來做到這一點:

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')

因此,從理論上講,這應該遍歷一列中的所有單元格,並且如果其中包含某些值,則將該值寫入此字典中的相應位置:

dataSet = {
'dates': [],
'ph': [],
'water_level': [],
'salinity': [],
'conductivity': [],
'tds': []
}

但是,有一個問題。 說完所有的話,字典看起來像:

{'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”為空。 這些確實是dataSet dict中的最后一個條目,所以也許這就是原因的一部分。 但是我只是不知道邏輯中的錯誤在哪里。

這是上下文文件的屏幕

有人可以幫忙嗎? 我真的很想打動我的老板;)(我不在IT部門工作,所以任何使人們的生活更輕松的計算機向導都充滿了驚奇和敬畏)。

如果我做得不夠好,無法確切解釋代碼在做什么,請告訴我,我將盡力澄清。

您可以嘗試這樣的事情:

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'少一個,因為在上面的函數調用中它的偏移量更大。

{u'foo': [2.3, 3.5, 5.6, 7.9], u'bar': [6.2, 3.6, 9L]}

此外,該代碼更輕便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM