Java实现Excel导入数据到数据库(支持xls、xlsx)

代码仅供参考,可根据实际业务实现具体逻辑

话不多说,上操作:

1.首先引入相关的依赖

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.1.19</version>
            <scope>compile</scope>
        </dependency>

ps:我的测试excel文件内容如下:

 2.新增测试实体类:

package com.fjqwkj.model;

/**
 * @author wdh
 * @create 2023-07-21 17:47
 * @desc
 **/
public class TestData {

    private String custName;
    private String pbkNum;
    private String phone;
    private String bankCard;

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getPbkNum() {
        return pbkNum;
    }

    public void setPbkNum(String pbkNum) {
        this.pbkNum = pbkNum;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getBankCard() {
        return bankCard;
    }

    public void setBankCard(String bankCard) {
        this.bankCard = bankCard;
    }
}

3.新建Excel工具类:

package com.fjqwkj.commons.utils;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.fjqwkj.model.TestData;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * @author wdh
 * @create 2023-07-21 15:27
 * @desc
 **/
public class HuToolExcelUtil {

    /**
     * 获取导入数据
     * @param bookStream 文件流
     * @param clazz 转换类
     * @param property 属性名
     * @param <T> 返回值
     * @return
     */
    public static <T> List<T> loadDown(InputStream bookStream, Class<T> clazz, String ...property) {
        ExcelReader reader = ExcelUtil.getReader(bookStream);
        Sheet sheet = reader.getSheet();
        Row sheetTitleRow = sheet.getRow(sheet.getFirstRowNum());
        int physicalNumberOfCells = sheetTitleRow.getPhysicalNumberOfCells();
        //获取表头数量
        int cellCount = 0;
        for (int i = 0; i < physicalNumberOfCells; i++) {
            Cell cell = sheetTitleRow.getCell(i);
            String stringCellValue = cell.getStringCellValue();
            if (StringUtils.isNotBlank(stringCellValue)) {
                cellCount += 1;
            }
        }
        if (property.length != cellCount) {
            throw new RuntimeException("指定属性数量与文件表头数不一致");
        }
        //替换标题为属性名
        for (int i = 0; i < cellCount; i++) {
            Cell cell = reader.getCell(i, 0);
            cell.setCellValue(property[i]);
        }
        return reader.readAll(clazz);
    }

    /**
     * 测试类
     * @param args
     * @throws FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException {
        InputStream is = new FileInputStream("C:\\Users\\28235\\Desktop\\11.xlsx");
        List<TestData> testDataList = HuToolExcelUtil.loadDown(is, TestData.class, "pbkNum", "phone", "custName", "");
        for (TestData testData : testDataList) {
            System.out.println("getCustName = " + testData.getCustName());
            System.out.println("getPbkNum = " + testData.getPbkNum());
            System.out.println("getPhone = " + testData.getPhone());
        }
        //todo 执行数据库保存操作即可
    }
}

4.main方法执行结果如下:

 ps:代码仅供参考,可根据实际业务,将excel数据保存到数据库即可

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Apache POI库来读取Excel文件中的数据,然后使用JDBC连接到数据库并将数据插入到数据库中。以下是一个简单的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; 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; public class ExcelToDatabase { public static void main(String[] args) { String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase"; String username = "myusername"; String password = "mypassword"; String excelFilePath = "data.xlsx"; try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) { FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheetAt(0); String sql = "INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); int rowNumber = 0; for (Row row : sheet) { if (rowNumber == 0) { rowNumber++; continue; } Cell cell1 = row.getCell(0); String column1 = cell1.getStringCellValue(); Cell cell2 = row.getCell(1); String column2 = cell2.getStringCellValue(); Cell cell3 = row.getCell(2); double column3 = cell3.getNumericCellValue(); statement.setString(1, column1); statement.setString(2, column2); statement.setDouble(3, column3); statement.addBatch(); if (rowNumber % 1000 == 0) { statement.executeBatch(); } } workbook.close(); statement.executeBatch(); System.out.println("Data imported successfully."); } catch (SQLException e) { System.out.println("Database error:"); e.printStackTrace(); } catch (Exception e) { System.out.println("Error:"); e.printStackTrace(); } } } ``` 请注意,此代码仅适用于Excel文件的第一个工作表,并且假定数据库中已经存在名为“mytable”的表,该表具有三个列:column1,column2和column3。您需要根据自己的需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值