在c#中的Excel工作表中查找最后一个填充的行

我有一个要求罚款有多less行在Excel表格填充数据即非空的行。 我需要使用c#来做到这一点。

目前我正在使用下面的代码:

Excel.Application excelApp = new Excel.Application(); string workbookPath = "C:\\ScriptTest\\bin\\Debug\\SDownloadScripts\\ExcelResult.xlsx"; 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); //long i = excelWorksheet.UsedRange.Rows.Count; int lastUsedRow = excelWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row; return lastUsedRow; } 

我的表只有四行填充,但我越来越65536.我需要4作为结果,即无行充满了一些数据。 请build议。

尝试这个..

 string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\xxxxxx\Desktop\1-8-13-ct.xlsx';Extended Properties=Excel 12.0;Persist Security Info=False"; //Create Connection to Excel work book OleDbConnection excelConnection =new OleDbConnection(excelConnectionString); //Create OleDbCommand to fetch data from Excel OleDbCommand cmd = new OleDbCommand("select count(*) from [Sheet1$]", excelConnection); con.Open(); int rows = (int)cmd.ExecuteScalar(); con.Close(); 

私人数据集CreateDataSource(stringstrFilePath,stringstrSheetName){数据集myDataSet; myDataSet = null; 尝试{

  if (strSheetName.Length > 0) { StringBuilder strConnectionString = new StringBuilder(); strConnectionString.AppendFormat("Provider={0};", "Microsoft.ACE.OLEDB.12.0"); strConnectionString.AppendFormat("Data Source={0};", strFilePath); strConnectionString.Append("Extended Properties="); strConnectionString.Append(((char)34).ToString()); //start of trickypart strConnectionString.Append("Excel 12.0 Xml;"); // always treat contents of cells as text, which gives us full control/responsibility for casting to numeric when ncessary strConnectionString.Append(((char)34).ToString()); // end of tricky part string str = strConnectionString.ToString(); OleDbConnection conn = new OleDbConnection(str); OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [" + strSheetName + "$] where QuestionDescription <>''", str); myDataSet = new DataSet(); myCommand.Fill(myDataSet); } else { trError.Visible = true; lblError.Text = "File is Invalid format"; } } catch { trError.Visible = true; lblError.Text = "Invalid format!!"; } return myDataSet; } 

对于使用上面的代码,您可以查询获取非空行。 结果将被存储到数据集中。 您可以从数据集中获得非空细胞计数。 对于此代码工作,您需要使用“Microsoft.ACE.OLEDB.12.0”提供程序。

我发现一些线程在stackoverflow问一个类似的问题。 也许这些已经解决了你的问题。 这个答案似乎是你在找什么。

根据你的结果, XlCelltype的文档和outcommented的行我假设你的工作表中usednange比实际使用的区域大。 如果另一个解决scheme不起作用,并且在你的数据行之间没有空行,那么你可以尝试在一个有空单元的列中search第一行(这行第1行应该是你所需要的行数)。