2016-02-11 62 views
0

我想創建一個字典,將項目代碼與其對應的總成本值相匹配。這些值位於不同的行和不同的列中。但是,還有其他單元可以被引用來獲取值。 Excel工作表看起來像這樣:使用python在不同的行和列中創建字典excel單元格

 A   B   C   D  E 
1 Project A1-234 Something Something 
2 does  not  matter 
3 Total          1234 
4 
5 Project A2-912 Something Something 
6 also  does  not  matter 
7 another will  not  matter 
8 Total          789 

項目代碼是關鍵,總值是字典的值。根據關的,我將有2鍵值對:

dict = { 
    "A1-234": 1234, 
    "A2-912": 789 
} 

有很多的項目,但他們都擁有這些一致性:

​​

什麼是創造這本字典的最佳方式?

+0

我無法想象一個簡單的解決方案,只是一堆if語句。 (例如,如果row [0] =='Project':key = row [1]; get_total = True) –

回答

0

這看起來很有前途。 xlrd and xlwt

我想我會用這個循環通過正則表達式的單元格,並追加到字典。我是python的新手,所以這可能不是一個好的解決方案。

0

這在技術上有效......如果您知道如何使代碼更漂亮,請讓我知道。

from xlrd import * 

# workbook containing the entire projects 
wb = open_workbook("C:/Users/my.name/Documents/Projects.xlsx") 
worksheet1 = wb.sheet_by_name("Sheet1") 

project_dict = {} 
project_key_column = 1 
total_value_column = 4 
total_found = True 
project_key = "" 

# store the project key and Total value into a dictionary 
for row_num in xrange(worksheet.nrows): 
    # find a row with Ai=Project and set project_key to the key value next to it 
    if worksheet.cell(row_num, 0).value == "Project": 
     if not total_found: # the total should be found before a second occurrence of Project 
      print "WARNING: Project %s did not find a value row" % project_key 
     project_key = worksheet.cell(row_num, project_key_column).value 
     total_found = False # find the value for the new Project key 

    # find a row with Ai=Total and set the value in the G column to total 
    if worksheet.cell(row_num, 0).value == "Total": 
     total = worksheet.cell(row_num, total_value_column).value 
     if total == "": 
      print "WARNING: Project %s contains an empty Value" % project_key 
     project_dict[project_key] = total # add the key value pair of the project_key and total 
     total_found = True 
相關問題