仅过滤c#中的excel文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15825302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:05:19  来源:igfitidea点击:

filtering only excel files in c#

c#

提问by G_S

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

我正在 C# 中处理 excel 表,我很震惊地只选择了 excel 表。我尝试了以下代码

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.

使用此代码不仅获得了 Excel 表格,而且最终获得了快捷方式文件。任何人都可以建议我如何限制快捷方式文件。

采纳答案by Vignesh.N

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;
}

回答by Ain Ronquillo

Try to use this. Hope this help! Cheers! :D

尝试使用这个。希望这有帮助!干杯! :D

browseFile.Filter = "Excel files (*.xls or .xlsx)|.xls;*.xlsx";

browseFile.Filter = "Excel 文件 (*.xls 或.xlsx)|.xls;*.xlsx";