Apache POI read Excel (before version 03)

Source: Internet
Author: User
Tags lenovo

One: First, the following three POI packages are imported:


Three bags above: http://download.csdn.net/detail/wangzihu/8420333

Two: Sample code

Package Com.lenovo.storage.web.util;import Java.io.bufferedinputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.text.decimalformat;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.Arrays; Import Java.util.date;import java.util.List; Import Org.apache.poi.hssf.usermodel.hssfcell;import Org.apache.poi.hssf.usermodel.hssfdateutil;import Org.apache.poi.hssf.usermodel.hssfrow;import Org.apache.poi.hssf.usermodel.hssfsheet;import Org.apache.poi.hssf.usermodel.hssfworkbook;import Org.apache.poi.poifs.filesystem.poifsfilesystem;import Com.lenovo.storage.common.model.admin.storageassetinfo;import Com.lenovo.storage.dao.storagedaofactory;public        Class exceltodata{public static void Main (string[] args) throws Exception {File File = new file ("E:/test.xls");       String[][] result = GetData (file, 1);       int rowlength = Result.length; list<object> addlist = newArraylist<object> ();       for (int i=0;i<rowlength;i++) {storageassetinfo sa=new storageassetinfo (); Sa.setproductname (result[i][0]);//Asset name Sa.setproducttime (result[i][1]);//Capitalization date Sa.setproductid (result[i][2]);       /Asset Serial number Sa.setcomment (Result[i][3]);//Assets Other Description Sa.setstatus (1);              Addlist.add (SA);              System.out.print (result[i][0]+ "\t\t");              System.out.print (result[i][1]+ "\t\t");              System.out.print (result[i][2]+ "\t\t");       System.out.println ();       } int Endresult=storagedaofactory.getcommondao (). Importexceldatatoasset (Addlist);       System.out.println ("Listsize:" +addlist.size () + "------insertresult:" +endresult);       if (endresult>0) {System.err.println ("Insert succeeded, insert" +endresult+ "bar Data"); }}/** * Reads the contents of Excel, the first-dimensional array stores the values of the columns in a row, how many rows are stored by the two-dimensional array * @param the source of the file reading data Excel * @param ignorerows read data ignored The number of rows, the figurative costume does not need to read into the number of ignored rows 1 * @return Read the contents of the data in Excel * @throws FILENOTFOUNDEXCEPtion * @throws IOException */public static string[][] GetData (file file, int ignorerows) throws file       Notfoundexception, IOException {list<string[]> result = new arraylist<string[]> ();       int rowsize = 0;       Bufferedinputstream in = new Bufferedinputstream (new FileInputStream (file));       Open Hssfworkbook Poifsfilesystem fs = new Poifsfilesystem (in);       Hssfworkbook wb = new Hssfworkbook (FS);      Hssfcell cell = null;          for (int sheetindex = 0; Sheetindex < wb.getnumberofsheets (); sheetindex++) {//To determine a few sheet, looping through these sheet corresponding Excel values       Hssfsheet st = Wb.getsheetat (Sheetindex); Hssfsheet st = wb.getsheetat (0);//Read the first sheet//first behavior header, without a for (int rowIndex = ignorerows; RowIndex <= ST.G Etlastrownum ();              rowindex++) {Hssfrow row = St.getrow (RowIndex);              if (row = = null) {continue;          } int temprowsize = Row.getlastcellnum () + 1;    if (Temprowsize > rowsize) {rowsize = temprowsize;              } string[] values = new String[rowsize];              Arrays.fill (Values, "");              Boolean hasValue = false;                  for (short columnindex = 0; columnindex <= row.getlastcellnum (); columnindex++) {String value = "";                  Cell = Row.getcell (columnindex);                      if (cell! = NULL) {//Note: Be sure to set this, otherwise garbled cell.setencoding (hssfcell.encoding_utf_16) may appear;                         Switch (Cell.getcelltype ()) {case hssfcell.cell_type_string:                         Value = Cell.getstringcellvalue ();                     Break                            Case HSSFCell.CELL_TYPE_NUMERIC:if (hssfdateutil.iscelldateformatted (CELL)) {                            Date date = Cell.getdatecellvalue ();                               if (date! = null) { Value = new SimpleDateFormat ("Yyyy-mm-dd"). Format (date);                            } else {value = ""; }} else {value = new DecimalFormat ("0"). Format (cell.getnumericcellval                         UE ());                     } break; Case Hssfcell.cell_type_formula://import if the data generated for the formula is no value if (!cell.getstringcellval                         UE (). Equals ("")) {value = Cell.getstringcellvalue ();                         } else {value = Cell.getnumericcellvalue () + "";                     } break;                     Case HSSFCell.CELL_TYPE_BLANK:break;                         Case HSSFCell.CELL_TYPE_ERROR:value = "";                     Break                 Case Hssfcell.cell_type_boolean:        Value = (Cell.getbooleancellvalue () = = true?                         "Y": "N");                     Break                     Default:value = ""; }} if (columnindex = = 0 && value.trim (). Equals ("")) {break                  ;                  } Values[columnindex] = Righttrim (value);              HasValue = true;              } if (HasValue) {Result.add (values);       }}//} in.close ();       string[][] ReturnArray = new String[result.size ()][rowsize];       for (int i = 0; i < returnarray.length; i++) {Returnarray[i] = (string[]) result.get (i);    } return ReturnArray; }/** * Remove the space to the right of the string * @param str to process the string * @return the processed string */public static string Righttrim (string       STR) {if (str = = null) {return "";       } int length = Str.length (); for (int i = LeNgth-1; I >= 0;           i--) {if (Str.charat (i)! = 0x20) {break;       } length--;    } return str.substring (0, length); }}


Apache POI read Excel (before version 03)

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.