2017-01-16 83 views
0

我想从excel文件创建一个层次结构。 样本数据如下:如何使用C#从excel文件创建一个类似于结构的树?

Path Description 
1   a 
1.1   b 
1.1.1  c 
1.2   d 
1.3   e 

现在,我需要阅读每一个细胞,并检查是否有子女或没有,

输出必须是,

Path   Description 
1    a 
1.1   b 
    1.1.1  c 
1.2   d 
1.3   e 

哪有我用C#实现这一点,并在控制台上打印? 请帮帮我。

+0

检查这个问题,这也回答了。 http://stackoverflow.com/questions/18316902/building-a-tree-with-parent-child-relationship-using-c-sharp-recursively –

+0

@KamilIbadov我面临的问题是如何检查点(。 )每次创建树状结构。 – user5928466

+0

对于每个单元格,您可以使用类似'var dotCount = cellValue.length - cellValue.replace(“。”,“”);'或'var dotCount = cellValue.split('。')的方式计算点数。长度;'。 – Serge

回答

0

我怀疑你在别的想要的东西,但你在用下面的代码回答问题:

var source = @"Path Description 
1   a 
1.1   b 
1.1.1  c 
1.2   d 
1.3   e"; 

var lines = 
    source 
     .Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 
     .Select(x => x.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); 

var results = 
    lines 
     .Skip(1) 
     .Select(x => new 
     { 
      Indent = x[0].Count(y => y == '.'), 
      Path = x[0], 
      Description = x[1] 
     }) 
     .Select(x => 
      String.Format(
       "{0}{1}{2}{3}", 
       "".PadLeft(x.Indent + 1).Substring(1), 
       x.Path, 
       "".PadLeft(15 - x.Path.Length - x.Indent), 
       x.Description)); 

Console.WriteLine(String.Join(Environment.NewLine, results)); 

它提供:

 
1    a 
1.1   b 
    1.1.1  c 
1.2   d 
1.3   e 
相关问题