|
As long as there are tables, there will be Microsoft Excel, and it has become a habit of many people to process data with Microsoft Excel. The Jakarta poi API provides a magical path for Java programmers to access Microsoft document formats. The most mature one is the hssf API that can access Microsoft Excel documents.
This article demonstrates how to use Java to create and read Excel documents and set the font and format of cells.
To ensure the running of the sample program, Java 2 sdk1.4.0 and Jakarta poi must be installed, and the Jakarta poi web site is: http://jakarta.apache.org/poi/
Create an Excel document
Example 1 demonstrates how to use the Jakarta poi API to create an Excel document.
Example 1 program is as follows:
Import org. Apache. Poi. hssf. usermodel. hssfworkbook;
Import org. Apache. Poi. hssf. usermodel. hssfsheet;
Import org. Apache. Poi. hssf. usermodel. hssfrow;
Import org. Apache. Poi. hssf. usermodel. hssfcell;
Import java. Io. fileoutputstream;
Public class createxl {
/** The location where the Excel file is to be stored. Assume that the file is in the jtest directory of drive D */
Public static string outputfile = "D:/jtest/gongye.xls ";
Public static void main (string argv []) {
Try {
// Create a new Excel Workbook
Hssfworkbook workbook = new hssfworkbook ();
// Create a worksheet in an Excel worksheet named the default value
// To create a worksheet named "benefit indicator", the statement is:
// Hssfsheet sheet = Workbook. createsheet ("benefit indicator ");
Hssfsheet sheet = Workbook. createsheet ();
// Create a row (the top row) at index 0)
Hssfrow ROW = sheet. createrow (short) 0 );
// Create a cell at index 0 (upper left)
Hssfcell cell = row. createcell (short) 0 );
// Define cells as strings
Cell. setcelltype (hssfcell. cell_type_string );
// Enter some content in the cell
Cell. setcellvalue ("added value ");
// Create an output file stream
Fileoutputstream fout = new fileoutputstream (outputfile );
// Save the corresponding Excel Workbook
Workbook. Write (fout );
Fout. Flush ();
// The operation ends. close the file.
Fout. Close ();
System. Out. println ("file generation ...");
} Catch (exception e ){
System. Out. println ("xlcreate ():" + E );
}
}
}
Read data from Excel documents |