Sidney
Sidney

Reputation: 65

Reading an Excel file UsedRange error

I basically need my code to read one by one all cells in an excel file and then upload then to a database.

I've read on several answers to this question I should use the UsedRange but everytime I do I get an error saying there is no definition for UsedRange.

I added a reference to the excel interop but no dice.

Any advice would be appreciated. And I know the code looks terrible now but I just wanted to test if I could read data from an excel file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication28
{
    class Program
    {
        static void Main()
        {
            Excel.Application excelApp = new Excel.Application();
            excelApp.Visible = true;

            string workbookPath = "C:/Users/Sidney/Desktop/CrystalViewer-11.xls";
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
                    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                    true, false, 0, true, false, false);

            Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            string currentSheet = "Sheet1";

            Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

            Excel.Range range;
            range = excelSheets.UsedRange;
            int rows_count = range.Rows.Count;
            string output = null; 
        }
    }
}

Upvotes: 1

Views: 2079

Answers (2)

Chethan Jain
Chethan Jain

Reputation: 1

Excel.Range xlRange = excelWorkbook.ActiveSheet.UsedRange;

Upvotes: 0

SBI
SBI

Reputation: 2322

You're trying to access UsedRange on the wrong Object. UsedRange is a property of Worksheet, so your code should be:

range = excelWorksheet.UsedRange;

Upvotes: 1

Related Questions