JXL Import and Export Excel

Source: Internet
Author: User

The import and export of Excel is often used in projects, and the more commonly used parsing rack packages are JXL and poi. Here we first introduce how JXL is implemented.

By referring to the online wording and my personal understanding:

Import Excel: Get an input stream from a local file, and then parse the data based on the structure of Excel.

Export Excel: Declares an output stream object, based on the parameters to get a workbook, to write the data. Then, based on the structure of the Excel table, you can add elements to workbook. Sheet, cell ....

Export Excel to export data containing pictures: JXL only supports images in PNG format.

To export an object to an Excel table: In fact, according to the object's property type, add the corresponding type of cell cell to sheet, such as the string corresponding to the new label, the picture corresponds to the labelimage, the integer number corresponding to the new numbers.

The two operations are implemented by a class:

 PackageWkl.util;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importjava.util.ArrayList;Importjava.util.List;ImportJXL. Cell;ImportJXL. Sheet;ImportJXL. Workbook;ImportJxl.write.Label;ImportJxl.write.WritableSheet;ImportJxl.write.WritableWorkbook;Importjxl.write.WriteException; Public classExceltest {/*** Important: According to the input stream to get an Excel document that is workbook, and then to parse workbook * JXL operation Excel table: Import: 2007 version does not support*/     Public Static voidImportex () {Workbook Workbook=NULL; Try {            //get an Excel documentWorkbook = Workbook.getworkbook (NewFileInputStream ("G:\\xx.xls")); //get a job this sheetSheet Sheet = Workbook.getsheet (0); //number of lines to get a work book            intTotalrows =sheet.getrows (); System.out.println ("Total number of rows =" +totalrows); //get number of columns            intcols =Sheet.getcolumns (); System.out.println ("Total number of columns =" +cols); //Traverse rows and columns (the No. 0 row is actually the title of the table and can be read from the first row to the data)             for(inti=0;i<totalrows;i++){                 for(intj=0;j<cols;j++) {cell cell= Sheet.getcell (J, I);//first row and thenString contents = cell.getcontents ();//get the contents of a cellSystem.out.println ("content =" +contents); }                            }        } Catch(Exception e) {e.printstacktrace (); }    }        /*** Main point: First through an output stream to get a work of this (Excel), and then just follow the structure of Excel to the Riga data * Export to the hard disk: 1, generate a job 2, create sheet 3, add cell label 4, write Data *@paramargs*/     Public Static voidExportex () {writableworkbook Book=NULL; Try {            //Create a work bookBook = Workbook.createworkbook (NewFileOutputStream ("g:\\ test. xls")); //Create a sheetWritablesheet sheet = book.createsheet ("First sheet", 0); //Create a labelLabel label =NewLabel (0,0, "name"); //Create a label twoLabel Label2 =NewLabel (1, 0, "age"); //Create Label3Label label3 =NewLabel (2,0, "gender"); List List=NewArrayList ();            List.add (label);            List.add (Label2);            List.add (LABEL3); //add label to sheet             for(intI=0;i<list.size (); i++{Sheet.addcell (Label) list.get (i)); }            //Write DataBook.write (); System.out.println ("Created successfully"); } Catch(Exception e) {e.printstacktrace (); }finally{            if(book!=NULL){                Try{book.close (); } Catch(WriteException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }    }

/**
* Picture writing: When the data that needs to be exported contains a picture
* @param args
*/
public static void Exportimg () {
Writableworkbook book = null;
try {
Book = Workbook.createworkbook (New File ("G:\\img.xls"));
Writablesheet sheet = book.createsheet ("picture", 0);

Only images in PNG format are supported
File Imgfile = new file ("G:\\test.png");//Picture data
Writableimage labelimage = new Writableimage (1, 4, 6, imgfile);
Sheet.addimage (Labelimage);
Book.write ();
} catch (Exception e) {
E.printstacktrace ();
}finally{
if (book!=null) {
try {
Book.close ();
} catch (WriteException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
}
/**
* Object data is written to Excel
*/
public void Writeexcel () {
Writableworkbook book = null;
try {
Open File
Book = Workbook.createworkbook (New File ("D:/test/stu.xls"));
Generate a worksheet named "Student", parameter 0 indicates this is the first page
Writablesheet sheet = book.createsheet ("student", 0);

List<student> stulist=student.querystudentlist ();
if (Stulist!=null &&!stulist.isempty ()) {
for (int i=0; i<stulist.size (); i++) {
Sheet.addcell (New Label (0, I, stulist.get (i). GetName ()));
Sheet.addcell (new number (1, I, Stulist.get (i). Getage ()));
}
}

Writing data and closing files
Book.write ();
} catch (Exception e) {
System.out.println (e);
}finally{
if (book!=null) {
try {
Book.close ();
} catch (Exception e) {
E.printstacktrace ();
}
}
}

} Public Static voidMain (String args[]) {//Importex ();Exportex (); }}

JXL Import and Export Excel

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.