Workbook讀取Excel數據


//讀取Excel
/*
*startRow 開始列
*endRow  結束列
* startCell 開始行
* endCell 結束行
 */

    public static Object[] [] readExcel(String  url,int startRow,int endRow,int startCell,int endCell){

        Object[] [] datas = new Object[endRow-startRow+1][endCell-startCell+1];
        //獲取Workbook對象
        try {
            File file = new File(url);
            Workbook workBook = WorkbookFactory.create(file);
            //獲取sheet 對象
            Sheet sheet =  workBook.getSheet("Sheet1");
            DataFormatter  formatter = new DataFormatter();
            //獲取行
            for(int i = startRow;i <= endRow;i++){
                Row row = sheet.getRow(i);
                for(int j = startCell;j <= endCell;j++){
                    Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    String value = formatter.formatCellValue(cell);
                    System.out.print(value+",");
                    datas[i-startRow][j-startCell] = value;
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return datas;
    }

需要jar

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-math3 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-math3</artifactId>
        <version>3.6.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.14.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.14.1</version>
    </dependency>

 


免責聲明!

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



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