Use POI Read EXCEL of the content
in many cases, the need to read EXCEL file. A simple example.
need to introduce a third party Jar Package: Poi_3.6.jar
Package com.daily;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.ArrayList;
Import java.util.List;
Importorg.apache.poi.hssf.usermodel.HSSFCell;
Importorg.apache.poi.hssf.usermodel.HSSFRow;
Importorg.apache.poi.hssf.usermodel.HSSFSheet;
Import Org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* simply read the content in Excel
* @author Fan Fangming
*/
public class Easyexcelread {
Privatelist<content> Readxls (String excelfile) throws IOException {
Inputstreamis = new FileInputStream (new File (Excelfile));
Hssfworkbookhssfworkbook = new Hssfworkbook (IS);
Contentcontent = null;
List<content>list = new arraylist<content> ();
// Looping Worksheets Sheet
for (int numsheet = 0; Numsheet < hssfworkbook.getnumberofsheets (); numsheet++) {
Hssfsheethssfsheet = Hssfworkbook.getsheetat (Numsheet);
if (Hssfsheet = = null) {
Continue
}
// Looping rows Row
for (int rowNum = 1; rowNum <= hssfsheet.getlastrownum (); rownum++) {
Hssfrowhssfrow = Hssfsheet.getrow (RowNum);
if (Hssfrow = = null) {
Continue
}
content= new Content ();
//0code;1 name
Hssfcellone = Hssfrow.getcell (0);
Content.setcode (GetValue (one));
Hssfcelltwo = Hssfrow.getcell (1);
Content.setname (GetValue ());
List.add (content);
}
}
returnlist;
}
/**
* get The values in the Excel table
*/
Privatestring GetValue (Hssfcell Hssfcell) {
if (hssfcell.getcelltype () = = Hssfcell.cell_type_boolean) {
// returns the value of a Boolean type
Returnstring.valueof (Hssfcell.getbooleancellvalue ());
}else if (hssfcell.getcelltype () = = Hssfcell.cell_type_numeric) {
// returns the value of a numeric type
Returnstring.valueof (Hssfcell.getnumericcellvalue ());
}else {
// returns the value of a string type
Returnstring.valueof (Hssfcell.getstringcellvalue ());
}
}
publicstatic void Main (string[] args) throws Exception {
Longstart = System.currenttimemillis ();
Easyexcelreadread = new Easyexcelread ();
List<content>contents = Read.readxls ("D:/ffm83/easyexcel.xls");
for (contentcontent:contents) {
System.out.println (Content.tostring ());
}
Longend = System.currenttimemillis ();
System.out.println (" generate Excel file time:" + (End-start) + "(ms)");
}
// a simple internal class for saving simple information
Publicclass Content {
Privatestring Code;
Privatestring name;
Publiccontent () {
}
Publiccontent (string code, string name) {
This.code= Code;
THIS.name = name;
}
Publicstring GetCode () {
ReturnCode;
}
Publicvoid Setcode (String code) {
This.code= Code;
}
Publicstring GetName () {
Returnname;
}
Publicvoid setName (String name) {
This.name= name;
}
@Override
Publicstring toString () {
Return "code:" + code + ", Name:" + name;
}
}
}
A good memory is better than a bad pen. 8-java reading Excel files