读EXCEL的内容写入到数据库

需要添加的依赖

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

代码

public static void main(String[] args) throws Exception {
        String jdbcURL = "jdbc:mysql://localhost:3306/buy";
        String username = "root";
        String password = "root";
        String excelFilePath = "H:\\新建文件夹\\日常工作.xlsx";

        try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {

            String sql = "INSERT INTO work (worktime, descri, name) VALUES (?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);

            FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
            Workbook workbook = WorkbookFactory.create(inputStream);
            //第一个sheet页
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row currentRow = rowIterator.next();
                Cell cell1 = currentRow.getCell(0);
                Cell cell2 = currentRow.getCell(1);
                Cell cell3 = currentRow.getCell(2);

                if (cell1 != null && cell2 != null && cell3 != null ) {
                    String column1 = cell1.getStringCellValue();
                    System.out.println(column1);
                    String column2 = cell2.getStringCellValue();
                    String column3 = cell3.getStringCellValue();

                    statement.setString(1, column1);
                    statement.setString(2, column2);
                    statement.setString(3, column3);
                    statement.executeUpdate();
                }
            }
            workbook.close();
            inputStream.close();
        } catch (SQLException | IOException ex) {
            ex.printStackTrace();
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值