读取Excel文件UsedRange错误

我基本上需要我的代码逐个读取excel文件中的所有单元格,然后上传到数据库。

我已经阅读了这个问题的几个答案,我应该使用UsedRange但每次我得到一个错误,说没有UsedRange定义。

我添加了对excel interop的引用,但没有骰子。

任何意见,将不胜感激。 而且我知道现在的代码看起来很糟糕,但我只是想testing一下,如果我可以从Excel文件中读取数据。

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

您正尝试访问错误对象上的UsedRangeUsedRange是Worksheet的一个属性,所以你的代码应该是:

 range = excelWorksheet.UsedRange;