JAVA读取Excel数据

1 创建Maven项目在pom文件中添加依赖

<dependencies>
        <!-- 旧的 .xls -->
        <!--<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>-->
        <!-- 新的 .xlsx -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
    </dependencies>

2 编写代码

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class PoiTest {
    public static void main(String[] args) throws IOException {
        FileInputStream is = new FileInputStream("src/main/resources/test.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        //读取Sheet
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        //获取最大行数
        int rownum = sheet.getPhysicalNumberOfRows();
        //获取最大列数
        int colnum = row.getPhysicalNumberOfCells();
        for (int i = 0; i < rownum; i++) {
            //获取第i行数据
            row = sheet.getRow(i);
            for (int j = 0; j < colnum; j++) {
                Cell cell = row.getCell(j);
                cell.setCellType(CellType.STRING);
                String cellText = cell.getStringCellValue();
                System.out.print(cellText + "\t");
            }
            System.out.println();
        }
    }
}

3 报错

3.1 异常解决Cannot get a STRING value from a NUMERIC cell poi

https://www.yuque.com/mengyingjie/micro/lttwq3

3.2 poi导出Excel报错java.lang.NoClassDefFoundError: org/openxmlformats/schemas/spreadsheetml/x2006/main/CTWorkbook$Factoryat

https://www.yuque.com/mengyingjie/micro/wakqgz

遇到此类问题,但看了文章还是未解决, 评论或加 QQ:781378815