【问题标题】:How to loop through and read the column headers in excel using epplus如何使用epplus循环读取excel中的列标题
【发布时间】:2014-09-02 17:30:59
【问题描述】:

我正在使用 epplus 读取一个 excel 文件,我想遍历每一行和每一列并查找列标题以检查集合并读取单元格值是否匹配。我是 epplus 的新手,找不到任何参考来做这样的事情。我在this link 中研究了类似的问题,但我没有通过列标题循环的东西。

有可能这样做吗?非常感谢任何帮助。

谢谢!

【问题讨论】:

  • 您提供的链接中的答案不是循环并获取标题吗?

标签: excel c#-4.0 epplus


【解决方案1】:

如果您想在 Excel 文件中找到与您指定的名称匹配的列,可以使用此函数:

    public string FindColumnAddress(ExcelWorksheet sheet, string columnName)
    {

        int totalRows = sheet.Dimension.End.Row;
        int totalCols = sheet.Dimension.End.Column;
        var range = sheet.Cells[1, 1, 1, totalCols];
        for (int i = 1; i <= totalCols; i++)
        {
            if (range[1, i].Address != "" && range[1, i].Value != null && range[1, i].Value.ToString() == columnName)
                return range[1, i].Address;

        }
        return null;
    }

它将返回列标题的地址。 您可以将其更改为返回 i 作为列的索引。

【讨论】:

    【解决方案2】:

    或者,如果您更喜欢使用 Linq 的解决方案:

        /// <summary>
        /// Get 1 based column number of first column with 'columnName' as column header
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="columnName">Column name to find</param>
        /// <returns>1 based column number if found or null if column not found</returns>
        public int? FindColumnAddress(ExcelWorksheet sheet, string columnName)
        {
    
            int totalCols = sheet.Dimension.End.Column;
            var header = sheet.Cells[1, 1, 1, totalCols].ToList();
    
            var idx = header.IndexOf(header.FirstOrDefault(hdritm => hdritm.Text == columnName));
    
            return idx < 0 ? (int?)null : idx + 1;
        }
    

    注意:如果您要检索许多列标题位置,您可能需要生成“标题”列表,然后使用 Linq 查询来检索每个列号,而无需重新构建列表每次搜索。

    我在这里找到了使用 IndexOf 的建议:

    Get List<> element position in c# using LINQ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多