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 a file
- if (!file.exists ()) {
- File.createnewfile ();
- }
- Writableworkbook workbook=workbook.createworkbook (file); //Create a workbook
- Writablesheet Sheet=workbook.createsheet ("Sheet1",0); Create sheet
- String[] title={"id","name","Age"}; Defining header Elements
- Populating 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 (); //Off
- }
- }
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 a working thin
- Sheet Sheet =workbook.getsheet (0); Get sheet
- int rows = Sheet.getrows (); //number of rows
- int columns = Sheet.getcolumns (); //Number of columns
- 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=New Getexceldata ();
- Ged.getdata ();
- }
- }
Test results:
Java Operations Excel table