2

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

3
  • I'm afraid you forgot the question.
    – aioobe
    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 ? Mar 3, 2011 at 15:14
  • If you're interested in using a library, Open CSV has come a long way: baeldung.com/opencsv Jan 15, 2019 at 4:33

4 Answers 4

3

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 :)

0
3

If you are using Java 6 you can use the Desktop class. Read also Opening, Editing, and Printing a File

2
  • 1
    A good point! But note, that Desktop.open(File file) method opens the file with a system default program, not with a specific one (like Excel in this case). It may well be that CSV would be set to be opened with another program, like Notepad++ or whatever.
    – Coryffaeus
    Mar 3, 2011 at 19:57
  • @Coryffaeus you are right. But IMHO it should be the user's choice what program opens csv-files. And the Desktop solution also handles the case when no Excel is installed. Mar 4, 2011 at 6:32
0

You can use JExcel API. It will be very easy for you.

0

For whatever reason, execString's provided did not work for me, but the one below worked:

String execString = "cmd /c start excel \"" + filePathString + "\"";

With the other exeString's I kept getting an exception saying that the runtime cannot find the file - start or excel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.