简体   繁体   中英

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; 
        }
    }
}

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

range = excelWorksheet.UsedRange;
Excel.Range xlRange = excelWorkbook.ActiveSheet.UsedRange;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM