How to Create Excel Spreadsheets Using Java

How to Create Excel Spreadsheets Using Java thumbnail
View a Java-generated spreadsheet in Microsoft Excel.

Business users can be particular. While Java's JTable presents data in a tabular form, some users just want to manipulate that data in Microsoft Excel. To satisfy such finicky users, you can generate a CSV file from Java and automatically launch Excel to view the data to keep them happy. The data placed into the CSV file can come from querying a JDBC data source or from parsing some XML files acquired from over your Internet connection, among many other possibilities.

Things You'll Need

  • Java Runtime Environment version 6 or above
  • Microsoft Excel
Show More

Instructions

    • 1

      Create a new file in your computer's text editor and save the file with the name Spreadsheet.java.

    • 2

      Include the Java I/O class library in the source code by adding the following line at the top of your file: import java.io.*;.

    • 3

      Generate your spreadsheet data as a set of lines with comma-separated values:

      public static String generateText() {

      return "1, 2, 3\r\n4, 5, 6\r\n7, 8, 9\r\n";

      }

    • 4

      Create a temporary file with a .csv extension to store the spreadsheet data:

      File file = File.createTempFile("test", ".csv");

    • 5

      Write the generated data to the file:

      PrintWriter pw = new PrintWriter(file);

      pw.write(text);

      pw.close();

    • 6

      Use the Microsoft Windows cmd shell to open the file:

      String[] cmd = new String[] {"cmd", "start", "/c", file.getPath()};

      Runtime.getRuntime().exec(cmd);

    • 7

      Save, compile and run your Spreadsheet program to see the generated CSV file in Microsoft Excel.

Tips & Warnings

  • You need to use \r\n in the generated text to separate rows in the spreadsheet data. You can also use the println() method of PrintWriter for the same purpose.

  • Linux users should replace the launching command with the following: cmd = new String[] {"soffice", file.getPath()};, assuming OpenOffice is available.

Related Searches:

References

Resources

  • Photo Credit number background image by kuhar from Fotolia.com

Comments

You May Also Like

Related Ads

Featured