2010-07-20 60 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