Check if Excel file is empty in C#

Go To StackoverFlow.com

1

Can anyone suggest, how to check if xls file empty or not? I have tried FileInfo("fname").Length == 0 But it's not working.

Thanks

2012-04-03 23:42
by Csharp_learner
Are you trying to avoid Excel automation - bouvierr 2012-04-03 23:47


4

An "empty" Excel file will still have an Excel file header, which is why your test for a size of 0 is failing.

You can use Excel Interop to see what the UsedRange is:

http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/b9cdfbd7-5ae9-41f7-b7e8-ebc00e835d45#546316e8-8745-42e8-9c0d-063d1373dfbe

2012-04-03 23:47
by Eric J.


1

for .xls you can try this - it works for me.

FileUpload1.SaveAs(Server.MapPath("~/FileUpload/") + path.Value);
                Workbook book = Workbook.Load(Server.MapPath(("~/FileUpload/") + FileUpload1.FileName));
                Worksheet sheet = book.Worksheets[0];
                sheetCount.Value = sheet.Cells.LastRowIndex.ToString();

                foreach (Worksheet ws in book.Worksheets)
                {
                    if (ws.Cells.Rows.Count != 0)
                    {
                        ddlSheets.Items.Add(ws.Name.ToString());
                    }
                }
2014-03-21 05:23
by user3418544


0

I think there is not simple solution similar to one you have stated.

You will have to actually programatically read the file by some Excel parser and check if there are some data.

2012-04-03 23:47
by Petr Újezdský