Tuesday 21 December 2021

How to get column names of a named range with column headers in C#.

 

How to get column names of a named range with column headers in C#.




This article explains how to retrieve the column names from a named range with column headers using XlsIO.

XlsIO does not have any direct way of retrieving column names from a named range with column headers. But there are few workarounds to achieve this. One way is exporting the named range to data table and retrieving the column names from data table. The alternate one is processing named range.

XlsIO always considers first row of named range as column header. So, the column names can be retrieved by accessing the first row of named range.

Download input file with data

Download complete sample

To know more about exporting data to data table, please refer the documentation.

The following complete code snippet explains how to retrieve column names of a named range with column headers by processing it.

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using Syncfusion.XlsIO;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
  
namespace ColumnNames_NamedRange
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                IApplication application = excelEngine.Excel;
                application.DefaultVersion = ExcelVersion.Excel2013;
  
                //Opening existing workbook with named range
                Assembly assembly = typeof(Program).GetTypeInfo().Assembly;
                Stream inputStream = assembly.GetManifestResourceStream("ColumnNames_NamedRange.Sample.xlsx");
                IWorkbook workbook = application.Workbooks.Open(inputStream);
  
               //Accessing named range
               IName namedRange = workbook.Names["DataValue"];
               List<string> columnName = new List<string>();
  
               int firstrow = namedRange.RefersToRange.Row;
  
               //Since the first row of named range is considered as column header, accessing the first row to get the column name
               for (int i = 1; i <= namedRange.RefersToRange.Columns.Length; i++)
               {
                   columnName.Add(namedRange.RefersToRange[firstrow, i].Text);
               }
  
               //Adding the column names to another worksheet
               IWorksheet worksheet = workbook.Worksheets.Create("Column Names");
  
               for (int i = 1, j = 0; i <= columnName.Count; i++, j++)
               {
                   worksheet[i, 1].Text = columnName[j];
               }
  
               //Saving the workbook as stream
               Stream outputStream = File.Create("Output.xlsx");
                workbook.SaveAs(outputStream);
            }
        }
    }
}

Git Basic working

  Develop = dev   r