How to read and write data from Excel in java

Source: Internet
Author: User

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 ();
}
}

Related Article

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.