2010-07-20 57 views
0

我的數據(電子表格):Django的遞歸樹與進口XLRD

'1',,, 
,'1.1',, 
,,'1.1.1', 
,,'1.1.2', 
,,'1.1.3', 
,'1.2',, 
,'1.3',, 
,,'1.3.1', 
,,'1.3.2', 
,,'1.3.3', 
'2',,, 
,'2.1',, 
,,'2.1.1', 
,,,'2.1.1.1' 
,,,'2.1.1.2' 
,,,'2.1.1.3' 

我的模型:

class Vocabulary(models.Model): 
    name = CharField(max_length=60) 

class Concept(models.Model): 
    parent = ForeignKey('self', blank=True, null=True) 
    vocabulary = ForeignKey(Vocabulary) 
    name = CharField(max_length=60) 
    order = IntegerField(default=0) 

我所試圖做的事:

def recurse(sheet): 
    'Recurse outer edges of the tree saving concepts.' 
     + 'Imply subtree order numbers. There are no numbers in the real data.' 

回答

2

這不是容易弄清楚,只是爲了分享它。這就是我如何使用Python XLRD和Django將層次結構從Excel導入到簡單的鄰接列表樹存儲。

class XLRDParseError(Exception): 
    """The XLS file was malformed.""" 

def load_xls(fname): 
    """Import a hierarchy into the DB from Excel""" 
    import xlrd 
    xlrd.open_workbook(fname) 
    firstSheet = book.sheet_by_index(0) 
    v = Vocabulary(title='New Import') 
    v.save() 
    vid = Vocabulary.objects.get(id=v.id) 
    conceptstack = [] 
    for row in range(firstSheet.nrows): 
     blank = 0 
     while True: 
      cell = firstSheet.cell(row, blank) 
      if cell.value: 
       break 
      blank += 1 
     concept = Concept(vocabulary=vid, name=cell.value) 
     concept.save() 
     if len(conceptstack) < blank: 
      raise XLRDParseError 
     if len(conceptstack) > blank: 
      for i in range(len(conceptstack) - blank): 
       conceptstack.pop() 
     if conceptstack: 
      concept.parent = conceptstack[-1] 
      concept.save() 
     conceptstack.append(concept) 

load_xls('/home/frank/top-navigation.xls') 

關鍵詞:層次,從Excel導入樹,進口逗號/製表符分隔的層次,從Excel,Python的Django的XLRD樹。進口類別

+1

任何特別的原因做'XLS =開放(FNAME).read (); book = xlrd.open_workbook(file_contents = xls)'而不是簡單的'book = xlrd.open_workbook(fname)'?注意:應該在'rb'模式下明確打開文件,以防某些Windows用戶盲目複製您的代碼。 [FWIW,我是xlrd的作者] – 2010-08-26 12:22:30

+0

沒有,現在看起來更乾淨。我不太在乎小平臺> :) – 2010-08-26 20:04:54