Excel package

The util.excel package contains some helper classes to generate excel (.xls) files. The package use jxl.jar library.

Library

The jxl.jar library was modified by the jptools project to switch the logger to the jptools logger. The changed class common.Logger which is in the jxl library is here available. The jptools modified library is here (jxl.jar) available.


Example

The following example generates an excel sheet testfile.xls. It contains one sheet (MyFirstSheet). The sheet has a title, a header and a data area. The data are random numbers. The result of the example below generates a file which looks like testfile.xls:

import jptools.util.RandomGenerator;
import jptools.util.excel.ExcelCellPosition;
import jptools.util.excel.ExcelLabel;
import jptools.util.excel.ExcelSheet;
import jptools.util.excel.ExcelWorkbook;

import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;


public class ExcelDemo
{
    public static void main( String[] args )
    {
        // create workbook
        WritableWorkbook workbook = ExcelWorkbook.getWorkbook( "testfile.xls", true );
        
        // create sheet
        WritableSheet sheet = ExcelSheet.createExcelSheet( null, workbook, "MyFirstSheet" );
        
        // define excel label
        ExcelLabel label = new ExcelLabel();
        
        // define label
        label.addTitleLabel( sheet, new ExcelCellPosition( "A1" ), "My Title" );
        
        // define header label
        label.addHeaderLabel( sheet, new ExcelCellPosition( "A3" ), "First Col" );
        label.addHeaderLabel( sheet, new ExcelCellPosition( "B3" ), "Second Col" );
        
        // define data position
        ExcelCellPosition dataStartPosition = new ExcelCellPosition( "A4" ); 
        
        // define column with
        ExcelSheet.setColumnView( sheet, dataStartPosition.getColumn(), 10000 );
        ExcelSheet.setColumnView( sheet, dataStartPosition.getColumn()+1, 10000 );
        
        int dataRow = dataStartPosition.getRow();
        for( int i = 0; i<100; i++ )
        {
            int dataCol = dataStartPosition.getColumn();
            
            for( int j = 0; j<2; j++ )
                label.addDataLabel( sheet, new ExcelCellPosition( dataCol++, dataRow ), 
                                    /* random data */ ""+RandomGenerator.getInstance().getRandomNumber( 100, true ) );
            
            dataRow++;
        }
        
        ExcelWorkbook.close( workbook );
    }
}