1. 先看Excel表格

2.导入依赖

  <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.2</version>
        </dependency>

3.读取Excel写入数据库

 public void getExcel() throws Exception {
              // 文件位置
        XSSFWorkbook workbook = new XSSFWorkbook("C:\\Users\\ASUS\\Desktop/a.xlsx");
        // 获取excel  第一个工作表
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        //获取最后一行行标,行标是从0开始,所以比实际行数小1
        int lastRowNum = sheetAt.getLastRowNum()+1;
        //  实体类
        ManyChoice manyChoice = new ManyChoice();
           // 如果你的第一行是标题 不需要添加 那 i就从1开始
            //  i表示从第几行开始
        for(int i=0;i<lastRowNum;i++){
            // 获取每一行
            XSSFRow row = sheetAt.getRow(i);
            // 获取单元格内容
            String title = row.getCell(0).getStringCellValue();
            String description = row.getCell(1).getStringCellValue();
            String answer = row.getCell(2).getStringCellValue();

          // 单元格int类型获取:  以double类型来接收获取的值,然后再转换为我们需要的int类型
            double s = row.getCell(3).getNumericCellValue();
            int score = new Double(s).intValue();

            //实体类赋值
            manyChoice.setTitle(title);
            manyChoice.setDescription(description);
            manyChoice.setAnswer(answer);
            manyChoice.setScore(score);

            // sql 添加语句
            manyChoiceMapper.insert(manyChoice);

        }


    }

4.数据库添加完成

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐