An Excel workbook has one or sereral sheets on a predefined order and each one have a unique name.

1 Columns

  • Versions till 11.0 could handle 256 columns (28 as label 'IV').
  • Version 12.0 onwards, including the current Version 16.x, can handle 16384 (214 as label 'XFD') columns.

Columns are inmaterial objects. You can not have a handler to a column other than it's index.

1.1 Getting last column

You can determinte the last populated column index by using getLastPopulatedColIndex() on sheet object.

1.2 Getting first column

You can determine the first populated column index by using getFirstPopulatedColIndex() on sheet object.

1.3 Column width

Given a shell you can use setColumnWidth(int columnIndex, int width) to set column width. The column index is the column to set (0-based) while with is expresed in units of 1/256th of a character width.

2 Rows

  • Versions of Excel up to 7.0 had a limitation in the size of their data sets of 16K (214 = 16384) rows.
  • Versions 8.0 through 11.0 could handle 64K (216 = 65536) rows and 256 columns (28 as label 'IV').
  • Version 12.0 onwards, including the current Version 16.x, can handle over 1M (220 = 1048576) rows, and 16384 (214 as label 'XFD') columns.

The row object is a representation of a row of a spreadsheet.

2.1 Getting rows

You can get a row by number and query the number of rows of a Sheet.

Return Method Description
JSExcelRow getRow(int row) Retuns an existing Row at given position or a newly created if it does not exists.
int getLastRowNum() Retuns the last row number (may be 0)

Notice that getting a row at given position ensures row exists so it will create a new one if need.

Copy
<script>
    
    var wb = new Ax.ms.Excel();
    var sheet = wb.createSheet("test");
    
    sheet.getRow(10);
    console.log(sheet.getLastRowNum());	

</script>
10

2.2 Iterate over rows

Sheet implements Iterable interface for it's rows. Also each Row implements Iterable interface for it's cells.

Copy
<script>
    var wb = Ax.ms.Excel.load("https://bitbucket.org/deister/axional-docs-resources/raw/master/Excel/Sample-sales.xls");
    var sheet = wb.getSheet(0);
    for (var row of sheet) {
        console.log("   Row = " + row.getRowNum());
        for (var cell of row) {
            console.log("     Cell: " + cell);
        }
    }
</script>

2.3 Convert row to Object[]

You can convert a Row to an Object[]

Copy
<script>
    var wb = Ax.ms.Excel.load("https://bitbucket.org/deister/axional-docs-resources/raw/master/Excel/Sample-sales.xls");
    var sheet = wb.getSheet(0);
    for (var row of sheet) {
    	console.log(row);
    	console.log(row.toArray());
    }
</script>

2.4 Adding rows

There are serveral methods to create new rows (or replace exising ones) from different data sources.

Return Method Description
Single row
Row addRow() Add a new empty row to the end of Sheet
Row addRow(Object[] data) Add an array of data as a new row to the end of Sheet
Row addRow(int startRow, int startCol, Object[] data) Add an array of data as a new row to Sheet at given row and start column. If row exists, it's content is replaced.
Multiple rows
int addRows(Object[][] data) Add a row for each array of data to the end Sheet.
int addRows(int startRow, int startCol, Object[][] data) Add a row for each array of data to Sheet starting at given row and column. If any row exists, it's content is replaced.
int addRows(ResultSet rs) Add a row for each ResultSet tuple to the end Sheet.
int addRows(String cellreference, ResultSet rs) Add ResultSet tuples as new rows to Sheet starting at given cell reference. If any row exists, it's content is replaced.
int addRows(ins startRow, int startCol, ResultSet rs) Add ResultSet tuples as new rows to Sheet starting at given row and col. If any row exists, it's content is replaced.

Copy
<script>
    var data = [
    	["1","China",                   1378020000,1578020000],
    	["2","India",                   1266884000,1366884000],
    	["3","United States of America", 323128000, 353128000],
    	["4","Indonesia",                257453000, 37453000 ],
    	["5","Brazil",                   206081000, 246081000]
    ];
    
    var wb = new Ax.ms.Excel("countries");
    var sheet = wb.createSheet("sheet1");
    sheet.addRows(1, 1, data);
</script>

2.5 Remove rows

You can remove rows from Sheet by using:

  • removeRows(int row) method.
  • removeRows(int start, int end) method. The operation will start from end to start to maximize speed as using this approach it will minimize shifts size (shift size will be 0 if end is equal to last row).

2.6 Clear rows

You can clear (remove) row cells from Sheet by using:

  • clearRow(int row) method.
  • clearRows(int start, int end) method.
  • clearRows(String cellrange) method.

2.7 Remove empty rows

Some times a sheet may contain empty rows that we don't use but are internally allocated. You can ensure to remove empty rows starting from end by using packRows() method.

When you call packRows() method, it will remove all empty rows starting from last row till first non empty row.

2.8 Shift rows

You can shift rows up or down on a sheet.

Copy
<script>

    // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
    sheet.shiftRows(5, 10, -5);

</script>

3 Cells

Even a cell belongs to a Row you can access cells directly from Sheet by using a cell reference or it's position.

3.1 Creating a cell

To get a cell on a Sheet use getCell

Return Method Description
JSExcelCell getCell(String cellreference) Returns an existing cell (or newly created if it does not exists) at given cell reference
JSExcelCell getCell(int row, int col) Returns an existing cell (or newly created if it does not exists) at given position

3.2 Getting cell content

To get the value of a cell in a Sheet use getCellValue

Return Method Description
Object getCellValue(String cellreference) Returns the value for a cell at given cell reference of null if it does not exists
Object getCellValue(int row, int col) Returns the value for a cell at given position of null if it does not exists

3.3 Setting cell content

To get the value of a cell in a Sheet use setCellValue

Return Method Description
JSExcelCell setCellValue(String cellreference, Object value) Sets the value for an existing cell (or newly created if it does not exists) at given cell reference
JSExcelCell setCellValue(int row, int col, Object value) Sets the value for an existing cell (or newly created if it does not exists) at given position

3.4 Setting cell styles

You can setup an individual cell style. But from Sheet you can also set cell style on a reange of cells.

Copy
<script>
    var data = [
    	["1","China",                   1378020000,1578020000],
    	["2","India",                   1266884000,1366884000],
    	["3","United States of America", 323128000, 353128000],
    	["4","Indonesia",                257453000, 37453000 ],
    	["5","Brazil",                   206081000, 246081000]
    ];
    
    // ==================================================================
    // Create an Excel workbook and sheet
    // ==================================================================
    var wb = new Ax.ms.Excel("countries");
    var sheet = wb.createSheet("sheet1");
    sheet.addRows(1, 1, data);
    
    // ==================================================================
    // Create an style and apply to numeric cells
    // ==================================================================
    var numberStyle = wb.createCellStyle();
    numberStyle.setDataFormat("#,##0");
    
    // set the numeric style to cells in range using col1, row1, col2, row2
    // or a cell range using: 
    // sheet.setCellStyle(numberStyle, "$C1:$D6");
    sheet.setCellStyle(numberStyle, 3, 1, 4, 6);
    
    // Auto resize sheet, as numbers take more space
    sheet.setAutoSizeColumns();
    
    // ==================================================================
    // Return Excel workbook as a Blob 
    // ==================================================================
    return wb;
</script>

3.5 Merging cells

You can merge and unmerge cells using a cell reference area.

Copy
<script>
    var wb = new Ax.ms.Excel("test");
    var sheet = wb.createSheet("sheet1");
    sheet.setMergedRegion("B2:F10");
    sheet.setBorders("B2:F10", Ax.ms.Excel.BorderStyle.MEDIUM);
    return wb.toBlob();
</script>

To remove a merged region simply call removeMergedRegion(String region)

4 Tables

To make managing and analyzing a group of related data easier, you can turn a range of cells into an Excel table (previously known as an Excel list).

You can create and empty table, a table for data array and a table from a ResultSet. In all cases you should provide a configurator for table settings.

4.1 Create default table

You can create a default table on a sheet for it's data content by simply using createTable() for the default style or createTable(String tableStyle) for a specific style.

Copy
<script>

    var wb = new Ax.ms.Excel();
    
    var sheet = wb.createSheet("sample");
    
    sheet.addRow(
        ["Date",	"Buyer",	"Type",	"Amount"]
    );
    
    sheet.addRows([
        [new Date(1,1,2019),	"Mom",	"Fuel",		74],
        [new Date(1,15,2019),	"Mom",	"Food",		235], 
        [new Date(1,17,2019),	"Dad",	"Sports",	20],
        [new Date(1,21,2019),	"Kelly","Books",	125], 
        [new Date(2,2,2019),	"Mom",	"Food",		235],
        [new Date(2,20,2019),	"Kelly","Music",	20],
        [new Date(2,25,2019),	"Kelly","Tickets",	125],
    ]
    );
    
    // Create a purble table style
    sheet.createTable("TableStyleMedium5");
    return wb;
</script>

4.2 Create an empty table

To create a simple table you simply need to specify it's range and a few options in provided table object. You can also configure it's style.

Copy
<script>
    var wb = new Ax.ms.Excel();
    var sheet = wb.createSheet("test");
    
    var colnames = ["b", "c", "d", "e", "f", "g", "h", "i", "j", "k"];
    sheet.createTable(colnames, (cttable, styleInfo) => {
        // Define area region (start row, start col, number of rows)
        cttable.setStartRow(1);
        cttable.setStartCol(1);
        cttable.setRows(8);
        cttable.setTotalsRowShown(false);
        
        // Configure table style
        styleInfo.setName("TableStyleMedium1");
        styleInfo.setShowColumnStripes(false);
        styleInfo.setShowRowStripes(true);
    });
    return wb.toBlob();
</script>

4.3 Create a table from data

To create a table from application data we simply pass the column names and the data array. Again, we need to setup the configurator for table location and style.

Copy
<script>

    var wb = new Ax.ms.Excel();
    var sheet = wb.createSheet("test");
    
    var cols = [ "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9" ];
    var data = [];
    for (var v = 0; v < 10; v++) {
        data.push([]);
        for (var i = 0; i < 10; i++) {
            data[v].push(i * v);
        }
    }
    
    sheet.createTable(cols, data, (cttable, styleInfo) => {
        // Define area region (start row, start col, number of rows)
        cttable.setStartRow(2);
        cttable.setStartCol(1);
        cttable.setTotalsRowShown(false);
    
        // Configure table style
        styleInfo.setName("TableStyleMedium2");
        styleInfo.setShowColumnStripes(false);
        styleInfo.setShowRowStripes(true);
    });
    
    return wb.toBlob();
</script>

4.4 Create table from ResultSet

In the following example we will create a table from a ResusultSet obtained from an external CSV.

Copy
<script>

    var wb = new Ax.ms.Excel();
    var sheet = wb.createSheet("test");
    
    // Load a CSV from from HTTPS
    var rs = new Ax.rs.Reader().csv(options => {
    	options.setResource("https://bitbucket.org/deister/axional-docs-resources/raw/master/CSV/antibiotics.csv");
    });
    
    sheet.createTable(rs, (cttable, styleInfo) => {
    
        // Define area region (start row, start col, number of rows)
        cttable.setStartRow(2);
        cttable.setStartCol(2);
        cttable.setTotalsRowShown(false);
    
        // Configure table style
        styleInfo.setName("TableStyleMedium3");
        styleInfo.setShowColumnStripes(false);
        styleInfo.setShowRowStripes(true);
    
    }).setAutoFilter();
    
    return wb.toBlob();

</script>

Notice we have enabled the autofilter feature in the table.

4.5 Table styles

You can access Excel built in styles using the static enum Ax.ms.Excel.TableStyle.

Copy
<script>
    for (var style of Ax.ms.Excel.TableStyle)
    	console.log(style);
</script>

Styles are numbered with colors. For TableStyleMedium it ranges from 1 to 25. A few colors example are shown below.

Style Color
TableStyleMedium1 Black
TableStyleMedium2 Blue
TableStyleMedium3 Red
TableStyleMedium4 Green
TableStyleMedium5 Purple
TableStyleMedium6 Cyan
TableStyleMedium7 Orange

5 Pivot tables

Pivot Tables are a powerful feature of spreadsheet files. You can create a pivot table with the following piece of code.

Copy
<script>

    var wb = new Ax.ms.Excel();
    
    var sheet = wb.createSheet("sample");
    
    sheet.addRow(
        ["Date",	"Buyer",	"Type",	"Amount"]
    );
    
    sheet.addRows([
        [new Date(2019, 1,  1),	"Mom",	"Fuel",		74],
        [new Date(2019, 1, 15),	"Mom",	"Food",		235], 
        [new Date(2019, 1, 17),	"Dad",	"Sports",	20],
        [new Date(2019, 1, 21),	"Kelly","Books",	125], 
        [new Date(2019, 2,  2),	"Mom",	"Food",		235],
        [new Date(2019, 2, 20),	"Kelly","Music",	20],
        [new Date(2019, 2, 25),	"Kelly","Tickets",	125],
    ]);
    
    // Create a purble table style
    sheet.createTable("TableStyleMedium5");
    
    var pivotTable = sheet.createPivotTable("A1:D8", "H5");
    pivotTable.addReportFilter(0);
    pivotTable.addRowLabel(1);
    pivotTable.addRowLabel(2);
    pivotTable.addColumnLabel(Ax.ms.Excel.DataConsolidateFunction.SUM, 3);
    return wb;
</script>

You can also create the pivot in another sheet making reference to data from other sheet.

Copy
<script>

    var wb = new Ax.ms.Excel();
    
    var sheet1 = wb.createSheet("sheet1");
    var sheet2 = wb.createSheet("sheet2");
    
    sheet1.addRow(
        ["Date",	"Buyer",	"Type",	"Amount"]
    );
    
    sheet1.addRows([
        [new Date(2019, 1,  1),	"Mom",	"Fuel",		74],
        [new Date(2019, 1, 15),	"Mom",	"Food",		235], 
        [new Date(2019, 1, 17),	"Dad",	"Sports",	20],
        [new Date(2019, 1, 21),	"Kelly","Books",	125], 
        [new Date(2019, 2,  2),	"Mom",	"Food",		235],
        [new Date(2019, 2, 20),	"Kelly","Music",	20],
        [new Date(2019, 2, 25),	"Kelly","Tickets",	125],
    ]);
    
    // Create a purble table style
    sheet1.createTable("TableStyleMedium5");
    
    var pivotTable = sheet2.createPivotTable("'sheet1'!A1:D8", "H5");
    pivotTable.addReportFilter(0);
    pivotTable.addRowLabel(1);
    pivotTable.addRowLabel(2);
    pivotTable.addColumnLabel(Ax.ms.Excel.DataConsolidateFunction.SUM, 3);
    return wb;
</script>

6 Splits and freeze panes

There are two types of panes you can create; freeze panes and split panes.

  • A freeze pane is split by columns and rows. You create a freeze pane using the following mechanism:

    Copy
    sheet1.createFreezePane( 3, 2, 3, 2 );

    The first two parameters are the columns and rows you wish to split by. The second two parameters indicate the cells that are visible in the bottom right quadrant.

  • Split panes appear differently. The split area is divided into four separate work area's. The split occurs at the pixel level and the user is able to adjust the split by dragging it to a new position.

    Split panes are created with the following call:

    Copy
    sheet2.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );
    • The first parameter is the x position of the split. This is in 1/20th of a point. A point in this case seems to equate to a pixel. The second parameter is the y position of the split. Again in 1/20th of a point.
    • The last parameter indicates which pane currently has the focus. This will be one of Sheet.PANE_LOWER_LEFT, PANE_LOWER_RIGHT, PANE_UPPER_RIGHT or PANE_UPPER_LEFT.

The following example shows how to use freeze and split panes.

Copy
<script>
    var wb = new Ax.ms.Excel("test");
    var sheet1 = wb.createSheet("new sheet");
    var sheet2 = wb.createSheet("second sheet");
    var sheet3 = wb.createSheet("third sheet");
    var sheet4 = wb.createSheet("fourth sheet");

    // Freeze just one row
    sheet1.createFreezePane( 0, 1, 0, 1 );
    // Freeze just one column
    sheet2.createFreezePane( 1, 0, 1, 0 );
    // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
    sheet3.createFreezePane( 2, 2 );
    // Create a split with the lower left side being the active quadrant
    sheet4.createSplitPane( 2000, 2000, 0, 0, sheet1.PANE_LOWER_LEFT );
 
    return wb.toBlob();
</script>

7 Autofilters

You can setup the the AutoFilter feature to find, show, or hide values—in one or more columns of data. You can filter based on choices you make from a list, or search to find the data that you seek. When you filter data, entire rows will be hidden if the values in one or more columns don't meet the filtering criteria.

Copy
<script>
    var wb = new Ax.ms.Excel();
    
    var sheet = wb.createSheet("data");
    sheet.setAutoFilter("A1:C11");
    for (var row = 1; row < 10; row++) {
    	for (var col = 0; col < 3; col++) {
    		sheet.setCellValue(row, col, Math.floor(Math.random() * 6) + 1);	
    	}
    }
    
    return wb;
</script>

You can see auto filters are present on worksheet.

8 Named ranges

You can create a named range to be used in formulas. In the following example we will create two named ranges one named "europe" and other "asia".

Copy
<script>
    // ===========================================================================
    // Create first sheet with European cities
    // ===========================================================================
    
    var sheet1 = wb.createSheet("Sheet1");
    
    sheet1.addRows([
        ["Barcelona", "BCN"],
        ["London",    "LON"], 
        ["Lisbon",    "LIS"], 
        ["Madrid",    "MAD"],
    ]
    );
    
    // Create the named range "europe" as Sheet1!$A$1:$B$4
    sheet1.createNamedRange("A1:$B4", "europe");
    
    // ===========================================================================
    // Create second sheet with Asian cities
    // ===========================================================================
    
    var sheet2 = wb.createSheet("Sheet2");
        
    sheet2.addRows([
        ["Singapur",    "SIN"], 
        ["Bankog", 		"BNK"],
        ["Tokio",    	"TOK"], 
        ["Deli",        "DEL"],
    ]
    );

    // Create the named range "asia" as Sheet2!$A$1:$B$4
    sheet2.createNamedRange("A1:$B4", "asia");
  
</script>

9 Data validation

You can setup data validation constaint on specific cell or range of cells. There are 5 validation types.

Type Description
Date Validation Enforces cell is a valid date
Integer Validation Enforces cell is a valid integer
Decimal Validation Enforces cell is a valid decimal
Length Validation Enforces cell has a maximum length
List Validation Enforces cell has a value from a drop down list
Formula List Validation It allows create a validation that takes it value(s) from a range of cells

9.1 Date validation

You can create d date validation constraint to enforce user enters a valid date.

Copy
<script>

    var wb = new Ax.ms.Excel("Workbook.xls");
    var sheet = wb.createSheet("Sheet1");
    sheet.addDateValidation("A1:A1");

    return wb.toBlob();
</script>

9.2 Integer validation

An integer validation constraint enforces data entered on cells are in the Integer range.

Copy
<script>

    var wb = new Ax.ms.Excel("Workbook.xls");
    var sheet = wb.createSheet("Sheet1");
    sheet.addIntegerValidation("A1:A1");

    return wb.toBlob();
</script>

You can set the limits of the validation constraint. For example, to only accept values between 0 and 100.

Copy
<script>

    var wb = new Ax.ms.Excel("Workbook.xls");
    var sheet = wb.createSheet("Sheet1");
    var validation = sheet.addIntegerValidation("A1:A1", 0, 100);
    return wb.toBlob();
</script>

9.3 Decimal validation

An decimal validation constraint enforces data entered on cells are in the Double range.

Copy
<script>

    var wb = new Ax.ms.Excel("Workbook.xls");
    var sheet = wb.createSheet("Sheet1");
    sheet.addDecimalValidation("A1:A1");

    return wb.toBlob();
</script>

9.4 Length validation

The length validation allows to restrict the input of a cell or range of cells to a maximum length.

Copy
<script>

    var wb = new Ax.ms.Excel("Workbook.xls");
    var sheet = wb.createSheet("Sheet1");
    sheet.addLengthValidation("A1:A1", 2);

    return wb.toBlob();
</script>

9.5 Single Drop Down List

In a excel sheet's cell we can provide drop list of possible value the cell can have. User can enter only specified value. On entering the wrong value, it will show error message like "The value you entered in not valid".

Copy
<script>
    var wb = new Ax.ms.Excel("Workbook.xls");
    
    var style_red   = wb.createCellStyle();
    style_red.setFont(wb.createFont().setColor(Ax.ms.Excel.Color.WHITE).setBold(true));
    style_red.setBorders(Ax.ms.Excel.BorderStyle.THIN);
    style_red.setFillPattern(Ax.ms.Excel.FillPatternType.SOLID_FOREGROUND);
    style_red.setFillForegroundColor(Ax.ms.Excel.Color.RED);
       
    // ===========================================================================
    // Create first sheet with European cities
    // ===========================================================================
    
    var sheet1 = wb.createSheet("Sheet1");
    
    sheet1.addRows([
        ["Barcelona", "BCN"],
        ["London",    "LON"], 
        ["Lisbon",    "LIS"], 
        ["Madrid",    "MAD"],
    ]
    );
    
    
    // ===========================================================================
    // Create second sheet with Asian cities
    // ===========================================================================
    
    var sheet2 = wb.createSheet("Sheet2");
        
    sheet2.addRows([
        ["Singapur",    "SIN"], 
        ["Bankog", 		"BNK"],
        ["Tokio",    	"TOK"], 
        ["Deli",        "DEL"],
    ]
    );
    
    // ===========================================================================
    // Create 3 combos with
    // a) list
    // b) data from sheet1
    // c) data from sheet2
    // ===========================================================================
    
    sheet1.setCellStyle(style_red, "$C2:$E2");
    sheet1.setCellValue("C1", "List(values)");
    sheet1.setCellValue("D1", "List($A$1:$A$5)");
    sheet1.setCellValue("E1", "List(Sheet2'!$A$1:$A$5)");
        
    sheet1.addListValidation("C2:C2", ["Very High","High","Medium", "Low", "Very Low"]);
    sheet1.addFormulaListValidation("D2:D2", "$A$1:$A$5");
    sheet1.addFormulaListValidation("E2:E2", "'Sheet2'!$A$1:$A$5");
    sheet1.setAutoSizeColumns();
    
    return wb.toBlob();
</script>

9.5.1 Dependent Drop Down Lists

In some cases, it may be necessary to present to the user a sheet which contains more than one drop down list. Further, the choice the user makes in one drop down list may affect the options that are presented to them in the second or subsequent drop down lists. One technique that may be used to implement this behaviour will now be explained.

There are two keys to the technique; one is to use named areas or regions of cells to hold the data for the drop down lists, the second is to use the INDIRECT() function to convert between the name and the actual addresses of the cells. In the example section there is a complete working example- called LinkedDropDownLists.java - that demonstrates how to create linked or dependent drop down lists. Only the more relevant points are explained here.

To create two drop down lists where the options shown in the second depend upon the selection made in the first, begin by creating a named region of cells to hold all of the data for populating the first drop down list. Next, create a data validation that will look to this named area for its data, something like this;

TO DO

This section is incomplete and will be concluded as soon as possible.
Copy

9.6 Dual Drop Down List

In Excel Drop Down lists will have only the value in the list. We can not have a display value and a stored value in the cell like in HTML combo boxes.

Let's see how to setup data Validation using a table with name and number pairs. This can be done with a NUMBER FORMAT trick, since the values you want to store in cell are numbers, but the values you want to show in the drop down are text.

If that were reversed this wouldn't work without VBA.

TO DO

This section is incomplete and will be concluded as soon as possible.

9.7 Formula List Validation

We have seen an example of Formula List validation in previous example when a combo of cities is generated from a cell range on cells from our sheet or from another sheet.

We can use the same function to generate data validation for functions like: INDIRECT(UPPER($A$1))

10 Conditional formatting

TO DO

This section is incomplete and will be concluded as soon as possible.
Copy
console.log(sheet.getSheetConditionalFormatting().toResultSet());

11 Sheet configuration

11.1 Set sheet zoom

You can setup the zoom level of any sheet using a percentaje scale. For example, to setup the sheet zoom at 150% do:

Copy
sheet.setZoom(150);

11.2 Set sheet as selected

To make a sheet as default selected

Copy
sheet.setSelected(true);

11.3 Fit Sheet to Page

To toggle sheet fits to page

Copy
sheet.setFitToPage(boolean mode);

11.4 Display grid lines

To toggle display of grid lines

Copy
sheet.setDisplayGridlines(boolean mode);

11.5 Hide or show a sheet

To toggle visibility of a sheet

Copy
sheet.setSheetHidden(boolean hidden);

11.6 Set print area for a sheet

TO DO

This section is incomplete and will be concluded as soon as possible.

11.7 Set page numbers on footer

TO DO

This section is incomplete and will be concluded as soon as possible.

12 Loading data

You can load data into a sheet either from application or database source.

12.1 Data from arrays

Creating data from JSON arrays is simple. By default, data is added at end of sheet by using:

  • addRow(int startRow, int startCol, Object[] data)
  • addRows(int startRow, int startCol, Object[][] data)

Copy
<script>

    var wb = new Ax.ms.Excel();
    var sheet = wb.createSheet("sample");
    
    sheet.addRow(
        [ "Date",	"Buyer",	"Type",	"Amount"]
    );
    
    sheet.addRows([
        [ new Date(1,1,2019),	"Mom",	"Fuel",		74],
        [ new Date(1,15,2019),	"Mom",	"Food",		235], 
        [ new Date(1,17,2019),	"Dad",	"Sports",	20],
        [ new Date(1,21,2019),	"Kelly","Books",	125], 
        [ new Date(2,2,2019),	"Mom",	"Food",		235],
        [ new Date(2,20,2019),	"Kelly","Music",	20],
        [ new Date(2,25,2019),	"Kelly","Tickets",	125],
    ]
    );

    return wb.toBlob();
</script>

12.2 Data from database

A common need is to generate a Workbook with database data. You can use high level buit in functions to do that. Let's see how to generate a Workbook directly from database.

12.2.1 Loading data from ResultSet

You can transfer ResultSet data to a sheet at a given location.

Copy
<script>    
    var wb    = new Ax.ms.Excel(Ax.ms.Excel.Type.XSSF, "dbexport.xlsx");
    var sheet = wb.createSheet("systables");
	var data  = Ax.db.executeQuery("SELECT * FROM systables");
	// Add a row with column names
    sheet.addHead(0, 0, data);
    // Add rows (starting at row 1 with data)
    sheet.addRows(1, 0, data);
    // create the a table surounding data (first row will be header row)
    sheet.createTable();
    return wb;
</script>

12.2.2 Creating a dbexport workbook manually

A more sophisticated way is to automatically generate a sheet from a ResultSet.

The function createSheet(String name, ResultSet data) will create a new sheet, add a row for column names, and setup data validations on each column according database types.

  • numbers will be validated as integer or decimals according their SQL type.
  • strings will be restricted to database column length.

The following example generates a Excel Workbook for given system tables.

Copy
<script>

    // Tables to add to Workbook (one sheet per table)
    var tables = [
        "systables",
        "sysprocedures",
    ];
    
    // use XSSF -> XLSX format
    var wb = new Ax.ms.Excel(Ax.ms.Excel.Type.XSSF, "dbexport.xlsx");
    
    var style_red   = wb.createCellStyle();
    style_red.setFont(wb.createFont().setColor(Ax.ms.Excel.Color.WHITE).setBold(true));
    style_red.setBorders(Ax.ms.Excel.BorderStyle.THIN);
    style_red.setFillPattern(Ax.ms.Excel.FillPatternType.SOLID_FOREGROUND);
    style_red.setFillForegroundColor(Ax.ms.Excel.Color.RED);
    
    var count = 0;
    for (table of tables) {
        count++;
        
        // Get table data
        console.log(Ax.text.String.format("[%4s of %4s] Loading table %s", count, tables.length, table));
        
        var columnNames = [];
        // Create a sheet named as table
        var sheet = wb.createSheet(table, options => {
            var pk_cols = Ax.db.getMetaData().getPrimaryKeyColumns(table);
            var order_by =  "";
            if (pk_cols && pk_cols.length > 0) {
                order_by =  " ORDER BY " + pk_cols.join();
            }
            var rs = Ax.db.executeQuery("SELECT * FROM " + table + order_by);
            options.setStartRow(0);
            options.setStartCol(0);
            options.setResultSet(rs);
            options.setOnCreateColumn(cell => {
            
                var columnName = cell.getColumnName();
                if (!rs.isColumnNullable(columnName)) {
                    cell.setCellStyle(style_red);
                }
                
                // keep column name to create later the table
                columnNames.push(columnName);
                
                // Add a cell comment with column type
                var text = rs.getColumnType(columnName);
                cell.setCellComment(text.replace(/<br\s*\/>/ig, "\n")); 
            });
        });
        var rows = sheet.getLastRowNum();
    	var cols = sheet.getLastColNum();
        
        // For XSSF we can create a Excel Table to decorate data
        if (wb.getType() == Ax.ms.Excel.Type.XSSF) {
            sheet.createTable(columnNames, (cttable, styleInfo) => {
                
                cttable.setRows(rows);
                cttable.setName(table);
                cttable.setDisplayName(table);
                
                styleInfo.setName("TableStyleMedium2");
                styleInfo.setShowColumnStripes(false);
                styleInfo.setShowRowStripes(true);
            });
        }
        
    	console.log(Ax.text.String.format("Exported table %s, %d row(s) x %d cols", table, rows, cols));
        sheet.setAutoSizeColumns();
    }

    return wb.toBlob();
</script>

This code is very similar that what will be done when using the Excel dbexport built in function described next.

13 Convert a sheet into ResultSet

You can easily convert a sheet into a memory ResultSet. For example, to convert first sheet into a ResultSet, taking first row as column names simply do:

Copy
<script>
    var wb = Ax.ms.Excel.load("file:/tmp/test.xlsx");
    let sheet = wb.getSheet(0);
    let rs = sheet.toResultSet();
    console.log(rs);
</script>
+------+------+---------+------+-----------+------------+------------+------+----------+------+ 
|<null>|<null>|<null>   |<null>|<null>     |<null>      |<null>      |<null>|<null>    |<null>| 
|Row   |A     |B        |C     |D          |E           |F           |G     |H         |I     | 
|object|object|object   |object|object     |object      |object      |object|object    |object| 
+------+------+---------+------+-----------+------------+------------+------+----------+------+ 
|1     |12.695|50042062L|S00042|16-abr-2020|2004-0646976|2005N-005317|100000|MASCARILLA|9     | 
|2     |10.630|46123748P|S00048|16-abr-2020|2004-0648259|2011N-014259|100000|MASCARILLA|9     |
+------+------+---------+------+-----------+------------+------------+------+----------+------+

Each colum is set to best SQL type according data content.