How to read and write data from Excel in java
Steps for reading and writing data from java to excel:
First, the jxl. jar package is required.
Read excel files:
Public class Test2 {
Public static void main (String [] args ){
Try {
Workbook book = Workbook. getWorkbook (new File ("test .xls "));
// Obtain the first worksheet object
Sheet sheet = book. getSheet (0 );
// Obtain the cell
For (int I = 0; I <sheet. getColumns (); I ++ ){
For (int j = 0; j <sheet. getRows (); j ++ ){
Cell cell = sheet. getCell (I, j );
System. out. print (cell. getContents () + "");
}
System. out. println ();
}
Book. close ();
} Catch (Exception e ){
System. out. println (e );
}
}
}
Write Data to excel:
/**
* Jxl xcel
*/
Public void writerJXL (){
Try {
Long dir = (long) Math. round (Math. floor (Math. random () * 10000000 ));
String dirPath = "c: // 11 //". concat (String. valueOf (dir ));
File file = new File (dirPath );
If (file. exists ()){
System. out. println (file. getName () + "Save xl ");
If (file. delete ()){
File. mkdir ();
}
} Else {
File. mkdir ();
}
// Input
Long l = (long) Math. round (Math. floor (Math. random () * 1000000000 ));
String name = "jxl _". concat (String. valueOf (l). concat (". xls ");
WritableWorkbook book = Workbook. createWorkbook (new File (dirPath. concat ("//"). concat (name )));
Int j = 0;
While (j <sheet) {// control heet Creation
WritableSheet sheet = book. createSheet ("test" + j, j );
Label label1 = null;
Label label2 = null;
For (int I = 0; I <leng; I ++ ){
Label1 = new Label (0, I, "A number xl" + I ); //
Label2 = new Label (1, I, "A number xl" + I );
Sheet. addCell (label1); // set
Sheet. addCell (label2 );
}
J ++;
}
Book. write ();
Book. close ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (RowsExceededException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Catch (WriteException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}