Java read Excel format xls, xlsx Data tool class

Source: Internet
Author: User

Support for jar packages that require POI


Call Mode:

Readexceltest exceltest = new Readexceltest (); Exceltest.readexcel ("d:\\data1.xlsx");

Package Com.util;import Java.io.file;import Java.io.fileinputstream;import java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstream;import Org.apache.poi.hssf.usermodel.hssfworkbook;import Org.apache.poi.ss.usermodel.cell;import Org.apache.poi.ss.usermodel.row;import Org.apache.poi.ss.usermodel.Sheet ; Import Org.apache.poi.ss.usermodel.workbook;import Org.apache.poi.xssf.usermodel.xssfworkbook;import Org.apache.xmlbeans.impl.piccolo.io.fileformatexception;public class Readexceltest {private static final String EXTEN    Sion_xls = "XLS";    private static final String extension_xlsx = "XLSX"; /*** * <pre> * Get workbook objects (XLS and xlsx objects are different, but are workbook implementation classes) * Xls:hssfworkbook * Xlsx:xssfworkboo K * @param filePath * @return * @throws IOException * </pre> * * Private Workbook Getworkbook (        String FilePath) throws IOException {Workbook Workbook = null;   InputStream is = new FileInputStream (FilePath);     if (Filepath.endswith (Extension_xls)) {workbook = new Hssfworkbook (IS);        } else if (Filepath.endswith (extension_xlsx)) {workbook = new Xssfworkbook (IS);    } return workbook;    }/** * File check * @param filePath * @throws filenotfoundexception * @throws fileformatexception */ private void Prereadcheck (String filePath) throws FileNotFoundException, fileformatexception {//General check File        File = new file (FilePath);        if (!file.exists ()) {throw new FileNotFoundException ("Incoming file does not exist:" + FilePath); } if (! ( Filepath.endswith (Extension_xls) | |        Filepath.endswith (extension_xlsx)) {throw new Fileformatexception ("Incoming file is not Excel"); }}/** * Read the contents of the Excel file * @param filePath * @throws filenotfoundexception * @throws fileformatexceptio        n */public void Readexcel (String filePath) throws FileNotFoundException, fileformatexception {//check ThIs.prereadcheck (FilePath);        Gets the Workbook object Workbook Workbook = null;            try {workbook = This.getworkbook (FilePath);                Read the file a sheet a sheet to read for (int numsheet = 0; Numsheet < workbook.getnumberofsheets (); numsheet++) {                Sheet Sheet = Workbook.getsheetat (Numsheet);                if (sheet = = null) {continue;                } System.out.println ("=======================" + sheet.getsheetname () + "=========================");                int firstrowindex = Sheet.getfirstrownum ();                int lastrowindex = Sheet.getlastrownum ();                Read the first line, the table header row firstrow = Sheet.getrow (Firstrowindex); for (int i = Firstrow.getfirstcellnum (); I <= firstrow.getlastcellnum (); i++) {Cell cell = FirstRow                    . Getcell (i);                    String Cellvalue = This.getcellvalue (cell, true); System.out.print ("" + CELLVAlue + "\ t");                } System.out.println ("");                    Read data row for (int rowIndex = Firstrowindex + 1; rowIndex <= Lastrowindex; rowindex++) { Row CurrentRow = Sheet.getrow (RowIndex);//Current line int firstcolumnindex = Currentrow.getfirstcellnum ();  first column int lastcolumnindex = Currentrow.getlastcellnum ();//last column for (int columnindex = Firstcolumnindex; ColumnIndex <= Lastcolumnindex;                        columnindex++) {Cell CurrentCell = Currentrow.getcell (columnindex);//Current cell String Currentcellvalue = This.getcellvalue (CurrentCell, true);//value of the current cell System.out.print                    Cellvalue + "\ t");                } System.out.println ("");            } System.out.println ("======================================================"); }} catch (Exception e) {E. Printstacktrace ();                } finally {if (workbook! = null) {try {workbook.close ();                } catch (IOException e) {e.printstacktrace (); }}}}}/** * takes the value of the cell * @param cell Cell Object * @param treatasstr is true, it is used as text to fetch values (text is not  Take "1" to "1.0") * @return * */private String Getcellvalue (cell cell, Boolean treatasstr) {if (cell = = null)        {return "";            } if (TREATASSTR) {//Although the text is set in Excel, the digital text is also read incorrectly, such as "1" Taken as "1.0"//plus the following sentence, temporarily read it as text        Cell.setcelltype (cell.cell_type_string);         } if (cell.getcelltype () = = Cell.cell_type_boolean) {return string.valueof (Cell.getbooleancellvalue ()); } else if (cell.getcelltype () = = Cell.cell_type_numeric) {return string.valueof (cell.getnumericcellval        UE ()); } else {return string.valueof (Cell.getstringcellvalue ()); }    }}


Java read Excel format xls, xlsx Data tool class

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.