【问题标题】:How can I create a tree like structure from excel file using C#?如何使用 C# 从 excel 文件创建树状结构?
【发布时间】:2017-01-18 15:07:44
【问题描述】:

我正在尝试从 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# 实现这一点并在控制台上打印? 请帮帮我。

【问题讨论】:

  • 检查这个问题也得到了回答。 stackoverflow.com/questions/18316902/…
  • @KamilIbadov 我面临的问题是如何每次都检查 Dots(.) 并创建树状结构。
  • 对于每个单元格,您可以使用 var dotCount = cellValue.length - cellValue.replace(".", "");var dotCount = cellValue.split('.').length; 之类的方式获取点数。
  • 查看此内容以计算字符串中字符的出现次数:stackoverflow.com/questions/541954/…

标签: c# excel


【解决方案1】:

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

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个 1.1 乙 1.1.1 c 1.2天 1.3e

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多