簡體   English   中英

如何使用C#從excel文件創建樹狀結構?

[英]How can I create a tree like structure from excel file using 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#實現此目標並將其打印在控制台上? 請幫我。

我懷疑您想要其他東西,但是您的問題使用以下代碼回答了:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM