Use POI to Operate Excel Code

Source: Internet
Author: User

I often encounter the need to store data in excel. Although it is not complicated to write data using POI, it is a bit annoying to write almost the same code every time. below is the code I often use, meeting the general requirements, advanced excel operations are not used, but should have met most of the requirements.

 

The jar package to be introduced is as follows,

Poi-2.5.1-final-20040804.jar

Poi-contrib-2.5.1-final-20040804.jar

Poi-scratchpad-2.5.1-final-20040804.jar

 

1. Excel class, representing an Excel object, which can contain many sheet and has the necessary methods,

 


Package stony. zhang. excel;

Import java. io. File;
Import java. io. FileInputStream;
Import java. io. FileNotFoundException;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. util. ArrayList;
Import java. util. List;

Import org. apache. poi. hssf. usermodel. HSSFCellStyle;
Import org. apache. poi. hssf. usermodel. HSSFFont;
Import org. apache. poi. hssf. usermodel. HSSFSheet;
Import org. apache. poi. hssf. usermodel. HSSFWorkbook;

Public class Excel {

Private boolean override;
Private String file;
HSSFWorkbook wb = new HSSFWorkbook ();
List <ExcelSheet> sheets = new ArrayList <ExcelSheet> ();

Private HSSFCellStyle titleStyle;
/**
* File, the file with the full path, If cant find, then new one.
*
* @ Param file
*/
Public Excel (String file ){
This (file, false );
}

Public Excel (String file, boolean override ){
This. file = file;
This. override = override;
File f = new File (file );
If (override ){
// Delete the exsited one
}
Try {
If (f. exists ()){
Wb = new HSSFWorkbook (new FileInputStream (file ));
} Else {
Wb = new HSSFWorkbook ();
}
TitleStyle = wb. createCellStyle ();
HSSFFont titleFont = wb. createFont ();
// TitleFont. setColor (HSSFFont. COLOR_RED );
TitleFont. setBoldweight (HSSFFont. BOLDWEIGHT_BOLD );
TitleStyle. setFont (titleFont );

// Create the Excel file.
Int num = wb. getNumberOfSheets ();
For (int I = 0; I <num; I ++ ){
HSSFSheet sheet = wb. getSheetAt (I );
String name = wb. getSheetName (I );
Sheets. add (new ExcelSheet (name, sheet, titleStyle ));
}
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}

/**
* @ Author Stony Zhang
* @ Date Feb 23,200 9
* @ Param sheetName
* If cant find the sheet, new one.
* @ Return
*/
Public ExcelSheet getSheet (String sheetName ){
For (ExcelSheet esh: this. sheets ){
If (esh. getName (). inclusignorecase (sheetName )){
Return esh;
}
}
HSSFSheet sheet = wb. createSheet (sheetName );
Return new ExcelSheet (sheetName, sheet, titleStyle );
}

Public void save (){
Try {
FileOutputStream fileOut = new FileOutputStream (file );
Wb. write (fileOut );
FileOut. close ();
} Catch (Exception e ){
// TODO: handle exception
}
}
 
Public static void main (String [] argv ){
Excel ex = new Excel ("E:/test.xls ");
ExcelSheet esh = ex. getSheet ("log ");
Esh. setHeader (new String [] {"User", "Table Name", "Database", "Action Type", "Opration Time "});
Esh. addRecord (new String [] {"aa", "bb", "cc", "dd", "ee "});
Ex. save ();
}

}
 

2. The ExcelSheet class represents a specific sheet.

Package stony. zhang. excel;
Import java. util. ArrayList;
Import java. util. List;

Import org. apache. poi. hssf. usermodel. HSSFCell;
Import org. apache. poi. hssf. usermodel. HSSFCellStyle;
Import org. apache. poi. hssf. usermodel. HSSFRow;
Import org. apache. poi. hssf. usermodel. HSSFSheet;

/**
* @ Author Stony Zhang
* @ Date Feb 23,200 9
* @ Return
*/
Public class ExcelSheet {
Private HSSFSheet sheet;

Private String name;

Private String [] header;

Private HSSFCellStyle titleStyle;

Public ExcelSheet (String sheetName, HSSFSheet sh ){
This. name = sheetName;
This. sheet = sh;
Sheet. setDisplayGridlines (true );
}
 
Public ExcelSheet (String sheetName, HSSFSheet sh, HSSFCellStyle titleStyle ){
This. name = sheetName;
This. sheet = sh;
This. titleStyle = titleStyle;
}

// Public ExcelSheet (){
// This (name );
//}

Public void addRecord (String [] record ){
If (header! = Null ){
If (header. length! = Record. length ){
Return;
}
}

FillContent (record, sheet. getLastRowNum () + 1, null );

}

Public String [] getHeader (){
Return this. header;
}

Public void setHeader (String [] header ){
This. header = header;
FillContent (header, 0, this. titleStyle );
}

Private void fillContent (String [] crow, int rowNum, HSSFCellStyle style ){
HSSFRow row = sheet. createRow (short) rowNum );

For (int I = 0; I <crow. length; I ++ ){
String s = crow [I];
HSSFCell cell = row. createCell (short) I );
If (style! = Null ){
Cell. setCellStyle (style );
}
Cell. setEncoding (HSSFCell. ENCODING_UTF_16 );
Cell. setCellValue (s );
}
}
 
Public void setValue (int rowNum, int colNum, String value ){
HSSFRow row = this. sheet. getRow (rowNum );
HSSFCell cell = row. getCell (short) colNum );
If (cell = null ){
Cell = row. createCell (short) colNum );
}
Cell. setEncoding (HSSFCell. ENCODING_UTF_16 );
Cell. setCellValue (value );
}

Public String getName (){
// TODO Auto-generated method stub
Return this. name;
}

Public void addRecord (ArrayList <String []> arr ){
For (String [] row: arr ){
This. addRecord (row );
}

}
 
Public List <String []> getRecords (){
ArrayList <String []> vs = new ArrayList <String []> ();
For (int j = 0; j <this. sheet. getLastRowNum (); j ++ ){
HSSFRow row = this. sheet. getRow (j );
ArrayList <String> cellsStr = new ArrayList <String> ();
For (short k = 0; k <row. getLastCellNum (); k ++ ){
HSSFCell cell = row. getCell (k );
If (cell! = Null ){
CellsStr. add (cell. getStringCellValue ());
}
}
System. out. println ("row =

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.