Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if file actually is an Excel file using EPPlus

Tags:

c#

excel

epplus

I'm using EPPlus in C# to read an Excel (.xlsx) file. The initialization is done like this:

var package = new ExcelPackage(new FileInfo(filename));

This works fine but is there any way to check if the specified filename or package is actually a valid .xlsx file? Otherwise there will be exceptions when operating on a non-Excel object, e.g. if the user accidentially opens a .zip file or else.

like image 811
Robert Strauch Avatar asked Feb 20 '13 15:02

Robert Strauch


People also ask

How can I tell if a file is Excel?

Check for the file extension 'xlsx' in the file name. However, to validate whether the selected file is actually an excel file,you need a library to validate such as Apache POI HSSF. Refer this answer for more information.

Does EPPlus require Excel?

No, it does not require Excel to be installed on the server, as you can read in the docs: EPPlus is a . NET library that reads and writes Excel files using the Office Open XML format (xlsx).

Does EPPlus work with XLS?

EPPlus does not work with the XLS format. Only XLSX. You'll need to find a new library.


1 Answers

You can check the extension of your file:

string file = @"C:\Users\Robert\Documents\Test.txt";

string extenstion = Path.GetExtension(file);

Update

I havent found some kind of return values for the situation that some file cannot be open in the EPPlus documentation, but you can use this to catch the excetptions:

FileInfo fileInfo = new FileInfo(pathToYourFile);

ExcelPackage package = null;
try
{
    package = new ExcelPackage(fileInfo);
}
catch(Exception exception)
{
   ...
}

If you are not in catch - thats mean it was opened correctly.

like image 192
MikroDel Avatar answered Sep 23 '22 08:09

MikroDel