[英]Reading Excel File in C# using MS Visual Studio 2010: How to give Relative Path?
I am reading an Excel file in the following way: 我正在通过以下方式读取Excel文件:
string path = @"C:\Users\myUserName\inputfile.xlsx";
Excel.Application app = new Application();
Excel.Workbook workbook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
I was wondering if there is any way I can give relative path instead of hard-coded absolute path. 我想知道是否有任何方法可以提供相对路径,而不是硬编码的绝对路径。 What I have in mind is to put the inputfile.xlsx in the same directory and do something like... 我要记住的是将inputfile.xlsx放在同一目录中并执行类似的操作...
string path = @"inputfile.xlsx";
But, it gives "COMException unhandled..", "inputfile.xlsx not found" 但是,它给出了“未处理COMException”,“找不到inputfile.xlsx”
use the following code to get the .exe location: 使用以下代码获取.exe位置:
string localPath = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetExecutingAssembly().Location)
You can use Directory.GetCurrentDirectory() to understand what your current directory is, if there is any doubt. 如有疑问,可以使用Directory.GetCurrentDirectory()来了解当前目录是什么。
If Excel is not finding the file, chances are very good that you misunderstand what the current directory is. 如果Excel找不到该文件,则很有可能会误解当前目录是什么。 Construct the path relative to the directory returned by GetCurrentDirectory(). 构造相对于GetCurrentDirectory()返回的目录的路径。
FYI, running the app stand-alone, in a debugger, and in a MS Test unit test will all set different current directories. 仅供参考,在调试器和MS Test单元测试中独立运行该应用程序将全部设置不同的当前目录。 The reason is that the executable is started from a different directory in each case. 原因是在每种情况下,可执行文件都是从不同的目录启动的。
Make sure the excel file is in the same folder as the executable, or alternatively make sure that the relative path is correct, relative to the directory containing the executable. 确保excel文件与可执行文件位于同一文件夹中,或者相对于包含可执行文件的目录,确保相对路径正确。
If the excel file is included in your project, you could also right click on it in the solution explorer, click on properties, and set the "Copy to Output Directory" to something like "Copy always". 如果项目中包含excel文件,也可以在解决方案资源管理器中右键单击它,单击属性,然后将“复制到输出目录”设置为“始终复制”。 This will cause the file to be placed in the projects output directory. 这将导致文件放置在项目输出目录中。 A relative path would then only include the name of the file. 相对路径将仅包含文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.