2016-02-11 17 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 
相关问题