I am making a project for college and have made a program which creates csv files. I would like there to be a button which you can click which then opens the csv file with excel. Thanks
-
I'm afraid you forgot the question.aioobe– aioobe2011-03-03 15:07:36 +00:00Commented Mar 3, 2011 at 15:07
-
Did you mean when you click a button made in java program, you should end up opening that .csv file ?Saurabh Gokhale– Saurabh Gokhale2011-03-03 15:14:02 +00:00Commented Mar 3, 2011 at 15:14
-
If you're interested in using a library, Open CSV has come a long way: baeldung.com/opencsvAdam Gerard– Adam Gerard2019-01-15 04:33:56 +00:00Commented Jan 15, 2019 at 4:33
4 Answers
Knowing that MsOffice is installed on the system, you should be able to open a document with it from command line using the command
excel myDoc.csv
to execute such a command from java, you could use this snapshot:
File myCSVFile; //reference to your file here
String execString = "excel " + myCSVFile.getAbsolutePath();
Runtime run = Runtime.getRuntime();
try {
Process pp = run.exec(execString);
} catch(Exception e) {
e.printStackTrace();
}
This is somewhat rough and needs styling, of course, but generally it should work. Besides, to be more graceful you could also check Windows registry, using the java.util.prefs.Preferences class, to know if MsOffice is installed and, if yes, where. But, please, be aware, if you are reckoning for MsExcel (as I understood from your post), this will automatically cancel Java's multiplatform approach. Hopefully, this helps :)
Comments
If you are using Java 6 you can use the Desktop class. Read also Opening, Editing, and Printing a File
2 Comments
Desktop solution also handles the case when no Excel is installed.