Nate
Nate

Reputation: 119

Getting a range of cell values into a list using closedXML and C#

I am using closedXMl to retrieve data from excel into my C# WPF. I am using the Range() function to manually select a range for data retrieval.

How can I get the values in the cells and store them into a list? Is there a way to work around this? Below is a sample of the method that I created to retrieve and store the excel data.

public List<double> TableList = new List<double>();

public void test()
    {
        using (var excelWorkbook = new XLWorkbook(@"D:\OneDrive ExcelFile.xlsx"))
        {
            var Ws = excelWorkbook.Worksheet("Sheet1");
            var TableList = Ws.Range("O18:O31");
        }

        for (int i = 0; i < TableList.Count; i++)
        {
            Console.WriteLine("{0}", TableList[i]);
        }
    }

The output I get is Sheet1!O18:O31

Upvotes: 4

Views: 13956

Answers (1)

Francois Botha
Francois Botha

Reputation: 4839

What you are currently writing to the console is the XLRange's default string implementation, which is the range address. If you want to the underlying cells' values in a list, use:

var tableList = Ws.Range("O18:O31")
    .CellsUsed()
    .Select(c => c.Value)
    .ToList();

Upvotes: 10

Related Questions