Search code examples
c#excelwinformscheckboxlist

C#- Pull column from Excel to a Checkbox list


I'm trying to pull the info in a column in excel and show it on a Checkbox List in Windows forms.

Right now I have a list of application names in an excel sheet, I am trying to put the cell values into a string array and attach it to the checklist box.

This is my forms class which handles the windows form:

 public Form1()
        {
            InitializeComponent();

            //FilesList filesList = new FilesList();
            //AppList testApp = new AppList();
            //filesList.DirSearch(@"C:\Users\dbell\Downloads\");

            Excel e = new Excel(@"SupportedApps.xlsx", 1);

            String[] list = e.ReadApplication();



            try
            {
                checkedListBox1.Items.AddRange(list);
            }
            catch (ArgumentNullException F)
            {
                Console.WriteLine("Error: " + F.ToString());
            }

        }

And this below is my poor attempt to create a method which returns a string array from my worksheet:

public string[] ReadApplication()
        {
            int column = 0;
            int row = 1;
            int stringNum = 0;
            string[] result = null;
            try
            {
                while (ws.Cells[row, column].Value2 != null)
                {
                    result[stringNum] = ws.Cells[row, column].Value2;
                    row++;
                    stringNum++;
                }
            }
            catch(NullReferenceException e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }


            return result;
        }

At the moment I keep getting null results. I have been able to get this working as a CSV file, however I would like to work with only one excel sheet.

Thanks in advance


Solution

  • Try to use https://www.nuget.org/packages/ClosedXML/ library.

            ClosedXML.Excel.IXLWorkbook workbook = new XLWorkbook(@"D:\Test.xlsx");
            var worksheet = workbook.Worksheets.First();
    
            int column = 1;
            int row = 1;
            int stringNum = 0;
            List<string> result = new List<string>();
            try
            {
                while (worksheet.Cell(row, column).Value != null && row < worksheet.RowCount())
                {
                    result.Add(worksheet.Cell(row, column).Value.ToString());
                    row++;
                    stringNum++;
                }
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }