open existing excel file in c# desktop application
I try to show an existing excel file when a user press the link which i开发者_高级运维s in my c# desktop application. I put my excel files into my project folder. nevertheless when I set up my project into different computers, paths of excel files will change. I couldn't find a way unrelated with direct path like C:\example.xlsx while opening excel files. How can I solve this problem? Thanks already..
I would suggest using the System.IO.Path.GetTempFileName() and copy the Excel file to the temporary file.
Or
Use the Application.StartupPath property.
If these files are stored inside your applicaton folder try to use:
string excelFilePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "excelfiles\\myexcelfile.xlsx");
Otherwise if you have predefined set of the files you need to have some setting where files are stored.
If you just need to allow user to specify where file stored - use OpenFileDialog
.
Two things:
If you don't mind MS GUI implementation, try the OpenFileDialog to let your user (if appropriate to do so) select the correct file:
var openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "xlsx files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
Edit:
Then use openFileDialog1.Filename
to get the filename.
OR
Use a relative path name if the file is always in the same relational directory:
StreamReader reader = new StreamReader("..\\'folder'\\'file'");
I find that one of these two ways will always work; dependant on if I want the user to choose the file or not.
Edit:
Once you have the file name, use Microsoft.Office.Interop.Excel
namespace to gain control of the file in excel, if that is desired.
Hope this helps!
精彩评论