Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8878097
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T19:37:50+00:00 2026-06-14T19:37:50+00:00

I have just written what has to be considered utterly hideous code to count

  • 0

I have just written what has to be considered utterly hideous code to count the rows that contain data in the worksheets called “Data” from all the spreadsheets in a given directory. Here’s the code

    private const string _ExcelLogDirectoryPath = @"..\..\..\..\Model\ExcelLogs\";
    static void Main()
    {
        var excelLogPaths = Directory.GetFiles(_ExcelLogDirectoryPath, "*.xl*");
        var excel = new Microsoft.Office.Interop.Excel.Application();
        var excelRowCounts = new Dictionary<string, int>();
        foreach (var filePath in excelLogPaths)
        {
            var spreadsheet = excel.Workbooks.Open(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "/" + filePath);
            var worksheet = spreadsheet.Sheets["Data"] as Worksheet;
            if (worksheet != null)
            {
                // var rowCount = UsedRange.Rows.Count - 1; DOES NOT WORK, THE number is bigger than the 'real' answer
                var rowCount = 0;
                for (var i = 1 ; i < 1000000000; i++)
                {
                    var cell = worksheet.Cells[i, 1].Value2; // "Value2", great name for a property, thanks guys
                    if (cell != null && cell.ToString() != "") // Very fragile (e.g. skipped rows will break this)
                    {
                        rowCount++;
                    }
                    else
                    {
                        break;
                    }
                }
                var name = spreadsheet.Name.Substring(spreadsheet.Name.IndexOf('p'), spreadsheet.Name.IndexOf('.') - spreadsheet.Name.IndexOf('p'));
                excelRowCounts.Add(name, rowCount - 1);
            }
        }

I cannot believe this is the right way to do this. It is crazy slow and includes calls to properties with names like Value2 that do not feel like an intended part of a public API. But the method suggested elsewhere dramatically over reports the number of rows (with data in them).

What is the correct was to count the rows with data in them from an Excel worksheet?

========== EDIT 1 ==========

The reason that both UsedRange.Rows.Count and Sid’s ACE.OLEDB solution over report the number of rows appears to be a pink background colour that is applied to some of the columns (but only extending to row 7091). Is there a simple/elegant way to count the rows with data in them (i.e. with non-null cell values) regardless of the display colour?

========== EDIT 2 ===========

Sid’s ACE.OLEDB solution with the addition he suggests so that the tSQL line reads

var sql = "SELECT COUNT (*) FROM [" + sheetName + "$] WHERE NOT F1 IS NULL";

works. I’ll mark that as the answer.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T19:37:51+00:00Added an answer on June 14, 2026 at 7:37 pm

    This should do the trick. You can call it with each filename to retrieve the number of rows.

    private string GetNumberOfRows(string filename, string sheetName)
    {
        string connectionString;
        string count = "";
    
        if (filename.EndsWith(".xlsx"))
        {
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 12.0;HDR=NO\"";
        }
        else if (filename.EndsWith(".xls"))
        {
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Mode=ReadWrite;Extended Properties=\"Excel 8.0;HDR=NO;\"";
        }
    
        string SQL = "SELECT COUNT (*) FROM [" + sheetName + "$]";
    
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            conn.Open();
    
            using (OleDbCommand cmd = new OleDbCommand(SQL, conn))
            {
                using (OleDbDataReader reader = cmd.ExecuteReader())
                {
                    reader.Read();
                    count = reader[0].ToString();
                }
            }
    
            conn.Close();
        }
    
        return count;
    }
    

    There might be an even faster way of retrieving just the row count, but I know this works.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just written a small piece of code and it struck me that
I have written come code that has worked on both Windows XP and Windows
I have just noticed that my simple program has its data and stack segments
I have web application written in java using Eclipse. It has just one servlet
I have written a following code to get just the file name without extension
I have written a SQL query that works just fine, but am having a
I have written a function that positions a tooltip just above a textbox. The
I have just written this code: EXl = ('C:\\vd36e404.vdb','C:\\vd368c03.vdb') x=0 for x in EXl:
We have an old (written in CakePHP 1.1!) application that has started groaning under
I have a file with saved data that sometimes needs to be accessed, written

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.