Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtering only excel files in c#

Tags:

c#

I am working on excel sheets in C# and i am struck to select only excel sheets. I tried the following code

OpenFileDialog browseFile = new OpenFileDialog();
browseFile.DereferenceLinks = true;
browseFile.Filter = "Excel|*.xls|Excel 2010|*.xlsx";
// browseFile.Filter = "Link Files (*.lnk)|*.lnk";

browseFile.Title = "Browse Excel file";
if (browseFile.ShowDialog() == DialogResult.Cancel)

Using this code am not only getting excel sheets but also ended up getting the shortcut files. Can anyone suggest how can i restrict the shortcut files too.

like image 785
G_S Avatar asked Apr 05 '13 03:04

G_S


People also ask

Can you automate filtering in Excel?

In addition to manual data filtering, Excel enables fully automated filtering based on data from the specified range of cells.


1 Answers

Please see if you are ok with the below approach.
In the meantime let me try if something is possible using reflections.

    OpenFileDialog openKeywordsFileDialog = new OpenFileDialog();
    openKeywordsFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    openKeywordsFileDialog.Multiselect = false;
    openKeywordsFileDialog.ValidateNames = true;
    openKeywordsFileDialog.DereferenceLinks = false; // Will return .lnk in shortcuts.
    openKeywordsFileDialog.Filter = "Excel |*.xlsx";
    openKeywordsFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(OpenKeywordsFileDialog_FileOk);
    var dialogResult =  openKeywordsFileDialog.ShowDialog();


void OpenKeywordsFileDialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
         OpenFileDialog fileDialog = sender as OpenFileDialog;
         string selectedFile = fileDialog.FileName;
         if (string.IsNullOrEmpty(selectedFile) || selectedFile.Contains(".lnk"))
         {
             MessageBox.Show("Please select a valid Excel File");
             e.Cancel = true;
         }
         return;
}
like image 72
Vignesh.N Avatar answered Sep 20 '22 23:09

Vignesh.N