简体   繁体   中英

Finding the last filled row in Excel sheet in c#

I have a requirement to fine how many rows in the Excel sheet are filled with the data ie rows which are not empty. I need to do that using c#.

Currently I am using the following code :

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

My sheet has only four rows filled but i getting 65536. I need 4 as a result ie no of rows filled with some data. Please suggest.

Try this..

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();

private DataSet CreateDataSource(string strFilePath, string strSheetName) { DataSet myDataSet; myDataSet = null; try {

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

for using above code you can query for to get non blank rows. the result will be stored into dataset. you can get non empty cell count from dataset. To this code work you need to use the "Microsoft.ACE.OLEDB.12.0" provider.

I found some threads on stackoverflow asking a similar question. Maybe these already solve your question. This answer seems to be what you are looking for.

Depending on your result, the documentation for XlCelltype and the outcommented line I assume that the usedRange in your sheet is bigger than the actually used area. If the other solution doesn't work and you have no empty rows between your datarows you maybe could try searching for the first row in a column which has an empty cell (this row-1 should than be your needed rowcount).

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