Home > database >  How to get list of .xlsx file in C#
How to get list of .xlsx file in C#

Time:12-16

I am developing Windows Form application and I want to have a list of .xlsx files in the folder say -

C:\Equipment\Exchanger\AES\

The folder may contain files like -

00-E-001,
00-E-002,
03-E-005,
04-E-001 and so on..

I don't want to open file dialogs but want to see a combo box showing the FileName (no extension). Based on selection of combobox I want to show the values of certain cells in the various text boxes but that is later part.

CodePudding user response:

You can use Directory.GetFiles to query the full path strings of every *.xlsx file in the folder, then strip it down to just the filename using Select and Path.GetFileName.. It makes sense (to me) to sort them alphabetically, then you just need them in a list so the combo can use them

yourCombo.DataSource = Directory.GetFiles(yourFolderPath, "*.xlsx").Select(Path.GetFileName).OrderBy(n => n.ToLower()).ToList();

If you don't want the extension in the combo (it's a waste of pixels :) ) you can use Path.GetFileNameWithoutExtension

When the time comes to get which file was selected by the user it's:

var fullPath = Path.Combine(yourFolderPath, yourCombo.SelectedItem);

(You'll have to add the extension back on if you used GetFilenameWithoutExtension: yourCombo.SelectedItem ".xlsx")


I recommend you set your combo's DropDownStyle to DropDownList

CodePudding user response:

First of all, your code should have a look at the folder, which contains needed files.

List<string> xlsxFiles = Directory.GetFiles(yourdirectory, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".xlsx" }
      .Contains(Path.GetExtension(file)))
      .ToList(); // Looking into directory and filtering files 

    for(int i = 0; i < xlsxFiles.Count; i  )
    {
        xlsxFiles[i] = Path.GetFileName(Path.ChangeExtension(xlsxFiles[i], null)); // Removes files' extensions
    }

This is the simple way of looking into the directory and filtering files to needed ones.

Then, I suggest having a look into EPPlus library, which allows you to work directly with tables and cells, without manual extraction of the file

Here is the handy tutorial of using EPPlus

  •  Tags:  
  • c#
  • Related