Java 中用POI lib读excel文件

来源:互联网 发布:123d建模软件 编辑:程序博客网 时间:2024/06/06 07:49

import org.apache.poi.hpsf.*
import org.apache.poi.hssf.usermodel.HSSFCell
import org.apache.poi.hssf.usermodel.HSSFRichTextString
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.DocumentInputStream
import org.apache.poi.poifs.filesystem.POIFSFileSystem

import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream

import java.util.Iterator

public class test{
   
    public void getContent(xlsPath) {
       
        InputStream inputStream = new FileInputStream (xlsPath)
        POIFSFileSystem fileSystem = new POIFSFileSystem (inputStream)
        HSSFWorkbook workBook = new HSSFWorkbook (fileSystem)
        HSSFSheet sheet = workBook.getSheetAt (0)
        Iterator<HSSFRow> rows = sheet.rowIterator ()
        while (rows.hasNext ())
        {
            HSSFRow row = rows.next ()
            //display row number in the console.
            System.out.println ("Row No.: " + row.getRowNum ())
            //once get a row its time to iterate through cells.
            Iterator<HSSFCell> cells = row.cellIterator ()
            while (cells.hasNext ())
            {
                HSSFCell cell = cells.next ()
                System.out.println ("Cell No.: " + cell.getCellNum ())
                /*
                 * Now we will get the cell type and display the values
                 * accordingly.
                 */
                if (cell.getCellType () == HSSFCell.CELL_TYPE_NUMERIC)
                {
                    // cell type numeric.
                    System.out.println ("Numeric value: " + cell.getNumericCellValue ())
                }
                else if (cell.getCellType () == HSSFCell.CELL_TYPE_STRING )
                {
                    // cell type string.
                    HSSFRichTextString richTextString = cell.getRichStringCellValue ()
                    System.out.println ("String value: " + richTextString.getString ())
                }
                else {
                    // types other than String and Numeric.
                    System.out.println ("Type not supported.")
                }
            }
        }
    }

}

 

API doc: http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html