Create an excel file
1: the basic principle is similar to reading workbooks. The first step is to create a writable workbook object.
Import java. io. File;
Import java. util. Date;
Import jxl .*;
Import jxl. write .*;
...
WritableWorkbook workbook = Workbook. createWorkbook (new File ("output.xls "));
The next step is to create a sheet for the workbook:
WritableSheet sheet = workbook. createSheet ("First Sheet", 0); // create a table named First Sheet at the beginning.
Now the remaining task is to add elements to sheet.
This is very simple, for example: to add 3.14159 to D5:
Number number Number = new Number (3, 4, 3.1459 );
Sheet. addCell (number );
In this way, you can add any amount of data, but you need to know the first point. When constructing a cell, the position of the cell in the worksheet is determined.
After a cell is created, the position of the cell cannot be changed, although the content of the cell can be changed.
Second, the cell is located according to the following rule (column, row), and the subscript starts from 0,
For example, A1 is stored in (0, 0), B1 is stored in (1, 0 ).
Finally,
Do not forget to close the opened Excel worksheet object to release the occupied memory. See the following code snippet:
// Write the Exel Worksheet
Wwb. write ();
// Close the Excel worksheet object
Wwb. close ();
Example:
Code (CreateXLS. java ):
// Generate an Excel class
Import java. io .*;
Import jxl .*;
Import jxl. write .*;
Public class CreateXLS
{
Public static void main (String args [])
{
Try
{
// Open the file
WritableWorkbook book =
Workbook. createWorkbook (new File ("zsa.xls "));
// Generate a worksheet named "first page". The parameter 0 indicates that this is the first page.
WritableSheet sheet = book. createSheet ("first page", 0 );
// In the constructor of the Label object, the cell position is the first row (0, 0) in the first column)
// And the cell content is test
Label label = new Label (0, 0, "zsa ");
// Add the defined cells to the worksheet
Sheet. addCell (label );
/* Generate a cell for saving numbers
The full package path of Number must be used; otherwise, the syntax is ambiguous.
The cell position is the second column, the first row, and the value is 1000.000 */
Jxl. write. Number number = new jxl. write. Number (1,0, 1000.000 );
Sheet. addCell (number );
// Write data and close the file
Book. write ();
Book. close ();
} Catch (Exception e)
{
System. out. println (e );
}
}
}
After compilation, an Excel file is generated at the current position.