Example of Creating Excel File with jxl.jar


Where can I find an example Java code that uses jxl.jar to create a new Excel file?

✍: FYIcenter.com


You can follow these suggestions and example to create a new Excel file with jxl.jar:

1. Create a writable workbook file using the factory method on the Workbook class:

WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));

The API can also be used to send the workbook directly to an output stream eg. from a web server to the user's browser. If the HTTP header is set correctly, then this will launch Excel and display the generated spreadsheet.

2. Create a sheet (tab) for the workbook. Again, this is a factory method, which takes the name of the sheet and the position it will occupy in the workbook. The code fragment below creates a sheet called "First Sheet" at the first position -

WritableSheet sheet = workbook.createSheet("First Sheet", 0);

3. Now all that remains is to add the cells into the worksheet. This is simply a matter of instantiating cell objects and adding them to the sheet. The following code fragment puts a label in cell A3, and the number 3.14159 in cell D5.

sheet.addCell(new Label(0, 2, "A label record")); 
sheet.addCell(new Number(3, 4, 3.1459));

Note that cell location index starts from 0. So location (0,2) is cell A3, and (3,4) is cell D5.

4. Once you have finished adding sheets and cells to the workbook, you call write() on the workbook, and then close the file. This final step generates the output file (output.xls in this case) which may be read by Excel. If you call close() without calling write() first, a completely empty file will be generated.


Here is the complete source code of example program JxlCreateExcel.java:

// Copyright (c) FYIcenter.com
// Example of creating a new Excel file
public class JxlCreateExcel {
   public static void main(String [] args) throws Exception {
	  jxl.write.WritableWorkbook workbook 
	     = jxl.Workbook.createWorkbook(new java.io.File("output.xls"));
      jxl.write.WritableSheet sheet = workbook.createSheet("First Sheet", 0);
      sheet.addCell(new jxl.write.Label(0, 2, "A label record")); 
      sheet.addCell(new jxl.write.Number(3, 4, 3.1459));

You can compile and run the above example in a command window as shown below:

   -cp .;\fyicenter\jexcelapi\jxl.jar JxlCreateExcel.java

   -cp .;\fyicenter\jexcelapi\jxl.jar JxlCreateExcel

The output file, output.xls, is ready for Microsoft Excel to open.


Java Source Code Example for jxl.jar

⇒⇒FAQ for Java Excel API jxl.jar

2018-02-21, 786👍, 0💬