如果选择的excel文件为空,请尝试catch [英] Try catch if selected excel file is blank

查看:87
本文介绍了如果选择的excel文件为空,请尝试catch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个使用vb.net中的oledb导入excel文件的程序。该程序将excel电子表格导入数据网格视图。打开程序时,将要求用户选择要打开的Excel文件,但是如果用户没有输入或按下取消按钮,程序将崩溃。我正试图找到一种方法来阻止用户取消或将excel文件名留空。我希望这可以使用try catch块完成,但我并不完全熟悉vb.net中的try catch。如果有人对此有任何建议或解决方案,我将不胜感激。这是我在MSDN上找到的。





Hello I have a program that imports an excel file using the oledb in vb.net. This program imports the excel spreadsheet into a datagridview. On opening the program will ask the user to choose an excel file to open, however if the user inputs nothing or presses the cancel button the program will crash. I'm trying to find a way to prevent a user from canceling or leaving the excel filename blank. I'm hoping this will be done using a try catch block but I'm not exactly familiar with try catch in vb.net. If anyone has any suggestions or solutions for this I would greatly appreciate it. This is what I found on MSDN.


Dim dlg As New OpenFileDialog()
        dlg.Filter = "Excel Macro Enabled Files|*.xlsm*|Excel Files|*.xls|Excel 2007 Files|*.xlsx|All Files|*.*"
        If dlg.ShowDialog() = DialogResult.OK Then
            '      excelObj = New ExcelObject(dlg.FileName)
            txtFilePath.Text = dlg.FileName

            Me.ExcelWriteBtn.Enabled = txtFilePath.Text.Length > 0
            Me.closexlsbtn.Enabled = txtFilePath.Text.Length > 0
        Else
            messagebox.show("Please Select a File")
            dlg.showdialog()
        End If

推荐答案

那么,为什么忽略空文件?这真的很重要吗我不认为人们创建空文档并故意保存为文件。它的概率几乎不会超过完全不相关甚至随机的Excel文档的概率。



所以,请查看我对该问题的评论。真正的问题是Excel不支持空文档的概念(例如,与纯文本文件不同)。你需要考虑这个标准是否有意义。我对此表示怀疑。







可能我误解了你。感谢ryanb31指出它。然后问题就简单多了,它只是简化为UI。当您说该程序将询问用户时,您应该正确询问。标准文件打开对话框返回反映用户决定的值。按下取消时,您知道返回值。该对话框不允许用户在没有取消的情况下选择任何文件。



就这么简单。



-SA
So, why ignoring "empty" documents? Is it really important. I don't think people create empty documents and save as files intentionally. The probability of it is hardly much more than the probability of totally irrelevant or even random Excel documents.

So, please look at my comment to the question. The real problem is that Excel does not support the concept of "empty document" (unlike plain text files, for example). You need to think if this criterion makes sense. I doubt it.



Probably I misunderstood you. Thanks to ryanb31 for pointing it out. Then the problem is much simpler, it is just reduced to UI. When you say "the program will ask the user", you should ask properly. The standard file open dialogs return the value which reflects the user's decision. When Cancel was pressed, you know that from return value. The dialog won't allow user to select no files without cancellation.

As simple as that.

—SA


这篇关于如果选择的excel文件为空,请尝试catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆