15.3. Creating SpreadsheetsThe API to create spreadsheets is somewhat different from the one that reads spreadsheets. In some sense the creation API is a higher level API because it deals with conceptual entities such as cells and fonts instead of underlying implementation entities such as Records. The general technique for creating a spreadsheet is as follows:
Step 5 can be repeated to create multiple cells in a row, step 4 can be repeated to create multiple rows in a sheet, and so on. Listing 15.6 shows these ideas in action. Listing 15.6. Creating a simple spreadsheetThis is a bit tedious but straightforward and effective. After running Listing 15.6, sample.xls will contain the spreadsheet shown in Figure 15.2 Figure 15.2. The spreadsheet created by Listing 15.6.![]() 15.3.1. FormattingAll of the formatting features available through Excel are also available through the APIs, although using them often requires a lot of code. Most formatting is done through the creation of HSSFCellStyle instances that contain information about fonts, colors, borders, and so on. These are then assigned to cells.For example, to make the "name" and "value" labels created by Listing 15.6 bold, blue, 16 points, and centered both vertically and horizontally, the style would first be created with the following code: Both labels would then be set to use this style with In addition, to accommodate the larger font, the row should be made taller. This can be done with an operation on the row that takes a size in a unit called "twips," equivalent to 1/20th of a point. It is also possible to add borders, although once again the process is somewhat tedious. To enclose the whole region, the "name" cell needs borders at the top and left, and the "value" cell needs borders at the top and right. This means they can no longer use the same HSSFCellStyle, even though their styles are otherwise identical. Likewise, the "A" and "B" cells need borders only on the left and the numbers only on the right. The bottom cells need borders on the left and bottom, and right and bottom, respectively. This means different HSSFCellStyles must be created. Borders are added to styles with various setBorder() methods; for example, the following specifies the borders for the "name" cell: With these additions to Listing 15.6 the generated spreadsheet will resemble Figure 15.3. Figure 15.3. The spreadsheet with some formatting. |