Java uses the poi package to read the Excel document code sharing, poiexcel

Source: Internet
Author: User

Java uses the poi package to read the Excel document code sharing, poiexcel

If the project needs to parse the Excel document to obtain data, you can find some information on the Internet. In combination with your own usage, write down your thoughts:

1. Add the following dependencies to the maven project:

<dependency>    <groupId>org.apache.poi</groupId>    <artifactId>poi</artifactId>    <version>3.10-FINAL</version>  </dependency>  <dependency>    <groupId>org.apache.poi</groupId>    <artifactId>poi-ooxml</artifactId>    <version>3.10-FINAL</version>  </dependency>

Directly test the class, which has a complete note:

Package shindo. java; import java. io. fileInputStream; import java. io. inputStream; import java. util. arrayList; import java. util. list; import org. apache. poi. hssf. usermodel. HSSFCell; 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. ss. usermodel. cell; import org. apache. poi. xssf. usermodel. XSSFCell; Import org. apache. poi. xssf. usermodel. XSSFRow; import org. apache. poi. xssf. usermodel. XSSFSheet; import org. apache. poi. xssf. usermodel. XSSFWorkbook; public class ExcelUtil {public static void main (String [] args) {String path = "D: \ IDE \ workspace-Neon \ Java \ src \ refund.xls "; try {List <String> result = new ExcelUtil (). readXls (path); System. out. println (result. size (); for (int I = 0; I <result. s Ize (); I ++) {List <String> model = result. get (I); System. out. println ("orderNum:" + model. get (0) + "--> orderAmount:" + model. get (1) ;}} catch (Exception e) {e. printStackTrace () ;}/ ***** @ Title: readXls * @ Description: process the xls file * @ param path * @ param @ return * @ param @ throws Exception setting file * @ return List <String> return type * @ throws ** from it is not difficult for the code to find its processing logic: * 1. use InputStream to obtain the excel file's io stream * 2. Then wear an in-memory excel file HSSFWorkbook type object, which represents the entire excel file. * 3. process each page of the excel file cyclically. perform cyclic processing on each line on each page * 5. process each cell in each row and obtain the value of this cell * 6. add the result of this line to a List array * 7. add the results of each row to the final summary result * 8. after parsing, a List <String> type object is obtained. **/private List <String> readXls (String path) throws Exception {InputStream is = new FileInputStream (path); // HSSFWorkbook identifies the entire excel HSSFWorkbook hssfWorkbook = new HSSFWorkbook (is ); list <String> result = new ArrayList <List <String> (); Int size = hssfWorkbook. getNumberOfSheets (); // loop each page and process the current cycle page for (int numSheet = 0; numSheet <size; numSheet ++) {// HSSFSheet identifies a page of HSSFSheet hssfSheet = hssfWorkbook. getSheetAt (numSheet); if (hssfSheet = null) {continue;} // process the current page and read each row cyclically for (int rowNum = 1; rowNum <= hssfSheet. getLastRowNum (); rowNum ++) {// HSSFRow indicates row HSSFRow hssfRow = hssfSheet. getRow (rowNum); int minColIx = hssfRow. GetFirstCellNum (); int maxColIx = hssfRow. getLastCellNum (); List <String> rowList = new ArrayList <String> (); // traverses and modifies rows to obtain and process each cell element for (int colIx = minColIx; colIx <maxColIx; colIx ++) {// HSSFCell indicates cell HSSFCell cell = hssfRow. getCell (colIx); if (cell = null) {continue;} rowList. add (getStringVal (cell);} result. add (rowList) ;}} return result;}/***** @ Title: readXlsx * @ Description: Process Xlsx text File * @ param path * @ param @ return * @ param @ throws Exception setting file * @ return List <String> return type * @ throws */private List <list <String> readXlsx (String path) throws Exception {InputStream is = new FileInputStream (path); XSSFWorkbook xssfWorkbook = new XSSFWorkbook (is ); list <String> result = new ArrayList <List <String> (); // loop each page and process the current cycle page for (XSSFSheet xssfSheet: xssfWorkbook ){ If (xssfSheet = null) {continue;} // process the current page and read each row for (int rowNum = 1; rowNum <= xssfSheet. getLastRowNum (); rowNum ++) {XSSFRow xssfRow = xssfSheet. getRow (rowNum); int minColIx = xssfRow. getFirstCellNum (); int maxColIx = xssfRow. getLastCellNum (); List <String> rowList = new ArrayList <String> (); for (int colIx = minColIx; colIx <maxColIx; colIx ++) {XSSFCell = xssfRow. getCell (colIx); if (Cell = null) {continue;} rowList. add (cell. toString ();} result. add (rowList) ;}} return result;} // problem/** in fact, sometimes the data we want to get is the data in excel, however, the final result is not satisfactory. * If the data in your excel is a number, you will find that the corresponding data in Java becomes a scientific notation. * When obtaining a value, you must perform some special processing to ensure that you can get the desired result. * The online approach is to format the numeric data and obtain the desired result. * Another method is provided below. Before that, let's take a look at the toString () method in poi: ** this method is a poi method. From the source code, we can find that, the process is: * 1. obtain the cell type * 2. format and output data based on the type. In this way, a lot of things are not what we want * so we need to make a transformation to this method. * // * Public String toString () {switch (getCellType () {case CELL_TYPE_BLANK: return ""; case CELL_TYPE_BOOLEAN: return getBooleanCellValue ()? "TRUE": "FALSE"; case CELL_TYPE_ERROR: return ErrorEval. getText (getErrorCellValue (); case CELL_TYPE_FORMULA: return getCellFormula (); case CELL_TYPE_NUMERIC: if (DateUtil. isCellDateFormatted (this) {DateFormat sdf = new SimpleDateFormat ("dd-MMM-yyyy") return sdf. format (getDateCellValue ();} return getNumericCellValue () + ""; case CELL_TYPE_STRING: return getRichStringCellValue (). toString (); defa Ult: return "Unknown Cell Type:" + getCellType () ;}} * // *** the default toString () method for poi transformation is as follows * @ Title: getStringVal * @ Description: 1. for unfamiliar types or null, return "" control string * 2. if it is a number, modify the cell type to String, and then return String, this ensures that the number is not formatted * @ param cell * @ param @ return setting file * @ return String return type * @ throws */public static String getStringVal (HSSFCell cell) {switch (cell. getCellType () {case Cell. CELL_TYPE_BOOLEAN: return cell. GetBooleanCellValue ()? "TRUE": "FALSE"; case Cell. CELL_TYPE_FORMULA: return cell. getCellFormula (); case Cell. CELL_TYPE_NUMERIC: cell. setCellType (Cell. CELL_TYPE_STRING); return cell. getStringCellValue (); case Cell. CELL_TYPE_STRING: return cell. getStringCellValue (); default: return "";}}}

Summary

The above is all the content about how to use the poi package in Java to read the Excel document code and share it. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.