Java讀取excel(兼容03和07格式)


讀取excel,首先需要下載POI的jar,可以去官網下,也可以在這里下載

一、簡單說明

excel2003和excel2007區別比較大,最直觀的感受就是擴展名不一樣,哈哈

不過,使用POI的API都是面向接口編程的,實際使用起來區別其實不大(知道為什么要面向接口編程了嗎?好處就在這里,O(∩_∩)O哈哈~)

代碼最直觀,直接看代碼

 

二、范例

 

package com.hundsun.excel.test;

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 EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";

    /***
     * <pre>
     * 取得Workbook對象(xls和xlsx對象不同,不過都是Workbook的實現類)
     *   xls:HSSFWorkbook
     *   xlsx:XSSFWorkbook
     * @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;
    }

    /**
     * 文件檢查
     * @param filePath
     * @throws FileNotFoundException
     * @throws FileFormatException
     */
    private void preReadCheck(String filePath) throws FileNotFoundException, FileFormatException {
        // 常規檢查
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("傳入的文件不存在:" + filePath);
        }

        if (!(filePath.endsWith(EXTENSION_XLS) || filePath.endsWith(EXTENSION_XLSX))) {
            throw new FileFormatException("傳入的文件不是excel");
        }
    }

    /**
     * 讀取excel文件內容
     * @param filePath
     * @throws FileNotFoundException
     * @throws FileFormatException
     */
    public void readExcel(String filePath) throws FileNotFoundException, FileFormatException {
        // 檢查
        this.preReadCheck(filePath);
        // 獲取workbook對象
        Workbook workbook = null;

        try {
            workbook = this.getWorkbook(filePath);
            // 讀文件 一個sheet一個sheet地讀取
            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();

                // 讀取首行 即,表頭
                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("");

                // 讀取數據行
                for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);// 當前行
                    int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
                    int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
                    for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
                        Cell currentCell = currentRow.getCell(columnIndex);// 當前單元格
                        String currentCellValue = this.getCellValue(currentCell, true);// 當前單元格的值
                        System.out.print(currentCellValue + "\t");
                    }
                    System.out.println("");
                }
                System.out.println("======================================================");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 取單元格的值
     * @param cell 單元格對象
     * @param treatAsStr 為true時,當做文本來取值 (取到的是文本,不會把“1”取成“1.0”)
     * @return
     */
    private String getCellValue(Cell cell, boolean treatAsStr) {
        if (cell == null) {
            return "";
        }

        if (treatAsStr) {
            // 雖然excel中設置的都是文本,但是數字文本還被讀錯,如“1”取成“1.0”
            // 加上下面這句,臨時把它當做文本來讀取
            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.getNumericCellValue());
        } else {
            return String.valueOf(cell.getStringCellValue());
        }
    }

}

 

三、其他

本人在Excel2010上試的時候,excel中明明設置的都是文本類型,但是讀取的時候,把數字“1”讀成“1.0”

所以在getCellValue()方法中,把cell單元格的式樣改了一下,確保數字“1”文本讀出來還是“1”

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM