The interaction between Java encoding and Excel is very much used in actual development, and today it is simple to use JXL to realize their interaction. Nonsense not much to say, direct code!
First, you have to import the JXL rack package:
1. Writing data to Excel
Package Com.easyteam.yc01;import Java.io.file;import JXL. Workbook;import Jxl.write.label;import Jxl.write.writablesheet;import Jxl.write.writableworkbook;public class operateexcel {public void Getexcel () throws exception{ file file = new file ("D:" +file.separator+ "A.xls");// Create File if (!file.exists ()) {file.createnewfile ();} Writableworkbook workbook=workbook.createworkbook (file);//Create Workbook Writablesheet sheet=workbook.createsheet ("Sheet1" , 0);//create sheetstring[] title={"id", "name", "Age"};//Define header element//populate the data into Excel for (int i=0;i<title.length;i++) {Label lable1=new label (I,0,title[i]);//table Header label lable2=new label (0,i+1,i+ "");//id label lable3=new label (1,i +1, "Zhang San" +i);//name label lable4=new label (2,i+1, "+i");//age Sheet.addcell (lable1); Sheet.addcell (lable2 ); Sheet.addcell (LABLE3); Sheet.addcell (LABLE4); } Workbook.write ();//write Data workbook.close ();//Close}}
Test:
Package Com.easyteam.yc01;public class Test {public static void main (string[] args) throws Exception {Operateexcel op=new Operateexcel (); Op.getexcel ();}}
Test results:
2. Read the data in Excel
Package Com.easyteam.yc01;import Java.io.file;import Java.io.ioexception;import JXL. Cell;import JXL. Sheet;import JXL. Workbook;import Jxl.read.biff.biffexception;import Jxl.write.writableworkbook;public class GetExcelData {public void GetData () throws exception{file file = new file ("D:" +file.separator+ "A.xls"); Workbook workbook=workbook.getworkbook (file);//Get Working thin sheet sheet =workbook.getsheet (0);//get sheetint rows = Sheet.getrows (); Number of rows int columns = Sheet.getcolumns ();//column number for (int i=0;i<rows;i++) {for (int j=0;j<columns;j++) {Cell cell= Sheet.getcell (J, I);//Get cell string str=cell.getcontents ();//Get cell contents System.out.print (str+ "\ t");} System.out.println ();}}}
Test:
Package Com.easyteam.yc01;public class Test1 {public static void main (string[] args) throws Exception {Getexceldata Ged=ne W Getexceldata (); Ged.getdata ();}}
Test results:
Java Operations Excel table