0

I'm trying to get data from Excel cells.

I'm using:

using Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;

'selectedRange' is null.

I have to use .Net 4.7.2

Code below

 private void exportButton_Click(object sender, EventArgs e)
        {
            Application excelApp = null;
            Range selectedRange = null;

            try
            {
                excelApp = (Application)Marshal.GetActiveObject("Excel.Application");
                selectedRange = excelApp.Selection as Range;

                if (selectedRange != null)
                {
                    var selectedValues = (object[,])selectedRange.Value;

                    var rowCount = selectedValues.GetLength(0);
                    var columnCount = selectedValues.GetLength(1);

                    for (var row = 2; row <= rowCount; row++)
                    for (var col = 1; col < columnCount; col++)
                    {
                        "work with data here"
                    }


                    excelApp.Quit();
                }
                else
                {
                    MessageBox.Show("Selection is Null");
                }
            }
            catch (COMException ex)
            {
                debugConsole.AppendText(ex + Environment.NewLine);
            }
            finally
            {
                if (selectedRange != null)
                    Marshal.ReleaseComObject(selectedRange);
                if (excelApp != null)
                    Marshal.ReleaseComObject(excelApp);
            }
        }
2
  • What do you think a selection is? What are you trying to do? Commented May 20, 2023 at 20:14
  • The first row in Excel is the keys, and each subsequent row is the values for a given key for a class of a certain object. I want to use excel table to use a loop and create or modify the values assigned to a given key for a given object. Commented May 20, 2023 at 20:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.