天天看點

java poi reader常用API彙總

 注意:

(1)判斷行的最大數量建議使用sheet.getLastRowNum();

(2)判斷每行最大列數建議使用row.getLastCellNum();

【JAVA】特别注意,POI中getLastRowNum() 和getLastCellNum()的差別
hssfSheet.getLastRowNum();//最後一行的下标,編号從0開始,即比行數小1。如果sheet中一行資料都沒有,則傳回-1,隻有第一行有資料時,傳回0
hssfSheet.getRow(k).getLastCellNum();//擷取列數,比最後一列列标大1.如果row中一列資料都沒有,則傳回-1,隻有第一列有資料時,傳回1      

getLastRowNum()擷取的是最後一行的編号(編号從0開始)。

int org.apache.poi.ss.usermodel.Sheet.getLastRowNum()

Gets the last row on the sheet

Returns: last row contained in this sheet (0-based)

getPhysicalNumberOfRows  
擷取有記錄的行數,即:最後有資料的行是第n行,前面有m行是空行沒資料,則傳回n-m;

getPhysicalNumberOfCells   
擷取有記錄的列數,即:最後有資料的列是第n列,前面有m列是空列沒資料,則傳回n-m;      

getPhysicalNumberOfRows()擷取的是實體行數,也就是不包括那些空行(隔行)的情況。

int org.apache.poi.ss.usermodel.Sheet.getPhysicalNumberOfRows()

Returns the number of physically defined rows (NOT the number of rows in the sheet)

java使用poi解析或處理excel的時候,如何防止數字變成科學計數法的形式
當使用POI處理excel的時候,遇到了比較長的數字,雖然excel裡面設定該單元格是文本類型的,但是POI的cell的類型就會變成數字類型。 
而且無論數字是否小數,使用cell.getNumbericCellValue() 去擷取值的時候,會得到一個double,而且當長度大一點的時候會變成科學計數法形式。 
那麼擷取這個單元格的原始的資料,就其實是一個double怎麼轉換成整數的問題了。 
使用DecimalFormat對這個double進行了格式話,随後使用format方法獲得的String就是你想要的值了。 
DecimalFormat df = new DecimalFormat("0");  
String whatYourWant = df.format(cell.getNumericCellValue());      

單元格内容換行:

Java利用POI生成Excel強制換行

1. 首先在需要強制換行的單元格裡使用poi的樣式,并且把樣式設定為自動換行

HSSFCellStyle cellStyle=workbook.createCellStyle();       
cellStyle.setWrapText(true);       
cell.setCellStyle(cellStyle);      

2. 其次是在需要強制換行的單元格,使用/就可以實再強制換行

換行用"\r\n",和文本分開

HSSFCell cell = row.createCell((short)0);    
cell.setCellStyle(cellStyle);                           
cell.setCellValue(new      
public class ImportExcel {
    
    private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
            
    /**
     * 工作薄對象
     **/
    private Workbook wb;
    
    /**
     * 工作表對象
     **/
    private Sheet sheet;
    
    /**
     * 标題行号
     */
    private int headerNum;
    
    /**
     * 構造函數
     * @param path 導入檔案,讀取第1個工作表
     * @param headerNum 标題行号,資料行等于标題行号+1
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(String fileName, int headerNum) 
            throws InvalidFormatException, IOException {
        this(new File(fileName), headerNum);
    }
    
    /**
     * 構造函數
     * @param path 導入檔案對象,讀取第1個工作表
     * @param headerNum 标題行号,資料行等于标題行号+1
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(File file, int headerNum) 
            throws InvalidFormatException, IOException {
        this(file, headerNum, 0);
    }

    /**
     * 構造函數
     * @param path 導入檔案
     * @param headerNum 标題行号,資料行等于标題行号+1
     * @param sheetIndex 工作表編号,以0開始
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(String fileName, int headerNum, int sheetIndex) 
            throws InvalidFormatException, IOException {
        this(new File(fileName), headerNum, sheetIndex);
    }
    
    /**
     * 構造函數
     * @param path 導入檔案對象
     * @param headerNum 标題行号,資料行等于标題行号+1
     * @param sheetIndex 工作表編号,以0開始、
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(File file, int headerNum, int sheetIndex) 
            throws InvalidFormatException, IOException {
        this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
    }
    
    /**
     * 構造函數
     * @param file 導入檔案對象
     * @param headerNum 标題行号,資料行等于标題行号+1
     * @param sheetIndex 工作表編号,以0開始、 
     * @throws InvalidFormatException 
     * @throws IOException 
     */


    /**
     * 構造函數
     * @param path 導入檔案對象
     * @param headerNum 标題行号,資料行等于标題行号+1
     * @param sheetIndex 工作表編号,以0開始、
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) 
            throws InvalidFormatException, IOException {
        if (StringUtils.isBlank(fileName)){
            throw new RuntimeException("導入文檔為空!");
        }else if(fileName.toLowerCase().endsWith("xls")){    
            this.wb = new HSSFWorkbook(is);    
        }else if(fileName.toLowerCase().endsWith("xlsx")){  
            this.wb = new XSSFWorkbook(is);
        }else{  
            throw new RuntimeException("文檔格式不正确?");
        }  
        if (this.wb.getNumberOfSheets()<sheetIndex){
            throw new RuntimeException("文檔中沒有工作表!");
        }
        this.sheet = this.wb.getSheetAt(sheetIndex);
        this.headerNum = headerNum;
        log.debug("Initialize success.");
    }
    
    /**
     * 擷取行對象
     * @param rownum
     * @return
     */
    public Row getRow(int rownum){
        return this.sheet.getRow(rownum);
    }

    /**
     * 擷取資料行号
     * @return
     */
    public int getDataRowNum(){
        return headerNum+1;
    }
    
    /**
     * 擷取工作表中的最後一行的行号,以0開始
     * @return
     */
    public int getLastDataRowNum(){
        return this.sheet.getLastRowNum();
    }
    
    /**
     * 擷取一行記錄總的列數
     * @return
     */
    public int getLastCellNum(){
        return this.getRow(headerNum).getLastCellNum();
    }
    
    /**
     * 擷取單元格的值
     * @param row 擷取的行
     * @param column 擷取單元格列号
     * @return 單元格的值
     */
    public Object getCellValue(Row row, int column){
        Object val = "";
        try{
            Cell cell = row.getCell(column);
            if (cell != null){
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
                    val = cell.getNumericCellValue();
                }else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
                    val = cell.getStringCellValue();
                }else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
                    val = cell.getCellFormula();
                }else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
                    val = cell.getBooleanCellValue();
                }else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
                    val = cell.getErrorCellValue();
                }
            }
        }catch (Exception e) {
            return val;
        }
        return val;
    }
    /**
     * 導入測試
     */
    public static void main(String[] args) throws Throwable {
        ImportExcel ei = new ImportExcel("import.xls", 0);
        System.out.println(ei.getLastDataRowNum());
        System.out.println(ei.getDataRowNum());
        
        for (int i = ei.getDataRowNum(); i <= ei.getLastDataRowNum(); i++) {
            Row row = ei.getRow(i);
            System.out.println("Row num:"+i);
            for (int j = 0; j < ei.getLastCellNum(); j++) {
                Object val = ei.getCellValue(row, j);
                System.out.print(val+", ");
            }
            System.out.print("\n");
        }
        
    }

}