You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Excel转MySQL的非Spring项目改造为Spring Boot REST服务

把Excel数据插入MySQL的现有代码改造为Spring Boot REST服务

我来帮你一步步完成改造,让你的功能可以通过REST API调用,并且返回指定的响应消息。下面是具体的实现步骤:

1. 创建Spring Boot项目并引入依赖

首先,创建一个新的Spring Boot项目,在pom.xml(Maven)或者build.gradle(Gradle)中添加以下必要依赖:

Maven依赖(pom.xml)

<dependencies>
    <!-- Spring Web 用于构建REST服务 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring JDBC 用于数据库操作 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- Apache POI 用于读取Excel文件 -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-hssf</artifactId>
        <version>5.2.5</version>
    </dependency>
</dependencies>

2. 重构核心业务代码为Spring Service

把原来的GITJapi类改成Spring的Service组件,移除TestNG相关注解,用Spring的方式管理依赖和操作。这里我们创建一个ExcelDataImporterService类:

package com.online.amazon.asinhunt.feature;

import com.online.amazon.asinhunt.dto.DBCloneDTO1;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;

@Service
public class ExcelDataImporterService {

    private final JdbcTemplate jdbcTemplate;

    // 构造注入JdbcTemplate(Spring自动管理)
    public ExcelDataImporterService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 获取Excel活动工作表
    private HSSFSheet getActiveSheet() throws Exception {
        File f = new File(".//testOCT_US.xls");
        try (FileInputStream fis = new FileInputStream(f);
             HSSFWorkbook book = new HSSFWorkbook(fis)) {
            return book.getSheetAt(0);
        }
    }

    // 读取Excel数据并插入数据库,返回插入的记录数
    public int importExcelData() throws Exception {
        HSSFSheet sheet = getActiveSheet();
        int existingRecordCount = getRecordCounts(38); // 替换原来的JDBCUtils.getRecordCounts逻辑
        int insertedCount = 0;

        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            // 只插入比现有记录数多的行(保留原逻辑)
            if (i > existingRecordCount) {
                // 读取单元格数据(注意处理空单元格)
                String rowNu = row.getCell(0, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                String testcaseId = row.getCell(1, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                String description = row.getCell(2, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                String priority = row.getCell(3, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                String buyer = row.getCell(4, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                String transactionData = row.getCell(5, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
                String dbValidation = row.getCell(6, Row.CREATE_NULL_AS_BLANK).getStringCellValue();

                DBCloneDTO1 dto = new DBCloneDTO1(rowNu, testcaseId, description, priority, buyer, transactionData, dbValidation);
                insertQuery(dto); // 执行插入
                insertedCount++;
            }
        }

        // 执行清理操作(保留原逻辑)
        cleanUp();
        return insertedCount;
    }

    // 替换原来的JDBCUtils.getRecordCounts方法
    private int getRecordCounts(int someParam) {
        // 这里替换成你的数据库查询逻辑,比如统计某表的记录数
        String sql = "SELECT COUNT(*) FROM your_table_name"; // 替换为实际表名
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    // 替换原来的JDBCUtils.insertQuery方法
    private void insertQuery(DBCloneDTO1 dto) {
        // 这里替换为你的插入SQL语句
        String sql = "INSERT INTO your_table_name (row_num, testcase_id, description, priority, buyer, transaction_data, db_validation) " +
                     "VALUES (?, ?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql,
                dto.getRowNu(),
                dto.getTestcaseId(),
                dto.getDescription(),
                dto.getPriority(),
                dto.getBuyer(),
                dto.getTransactionData(),
                dto.getDbValidation());
    }

    // 清理目录的方法(保留原逻辑)
    private void cleanUp() throws Exception {
        boolean condition = isDeleteDirectory(new File(".//clone1//"));
        if (condition) {
            System.out.println("Cleanup completed");
        }
    }

    private boolean isDeleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (null != files) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        isDeleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
        }
        return directory.delete();
    }
}

3. 编写REST Controller

创建一个Controller类,暴露REST端点,调用Service的导入方法,并返回指定响应:

package com.online.amazon.asinhunt.controller;

import com.online.amazon.asinhunt.feature.ExcelDataImporterService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExcelImportController {

    private final ExcelDataImporterService importerService;

    public ExcelImportController(ExcelDataImporterService importerService) {
        this.importerService = importerService;
    }

    @PostMapping("/api/import-excel")
    public ResponseEntity<String> importExcel() {
        try {
            int insertedCount = importerService.importExcelData();
            if (insertedCount > 0) {
                return ResponseEntity.ok("记录已插入");
            } else {
                return ResponseEntity.ok("No record inserted.");
            }
        } catch (Exception e) {
            // 处理异常,返回错误信息
            return ResponseEntity.internalServerError().body("导入失败:" + e.getMessage());
        }
    }
}

4. 配置数据库连接

在src/main/resources/application.properties中添加MySQL数据库配置:

# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 可选:开启SQL日志(方便调试)
spring.jdbc.template.query-timeout=30
logging.level.org.springframework.jdbc.core=DEBUG

关键说明

  • 我把原来的TestNG相关注解全部移除,改用Spring的@Service和@RestController来管理组件。
  • 用Spring的JdbcTemplate替换了原来的JDBCUtils,这是Spring Boot中推荐的JDBC操作方式,不需要自己管理连接。
  • 保留了你原来的核心业务逻辑:读取指定路径的Excel文件、只插入新记录、清理目录。
  • Controller中的POST /api/import-excel端点就是你要的触发入口,调用后会返回对应的成功/提示消息,异常时会返回错误信息。

如果你想让Excel文件路径更灵活,可以把路径配置到application.properties中,比如:

excel.file.path=.//testOCT_US.xls

然后在Service中用@Value("${excel.file.path}")注入这个路径。

内容的提问来源于stack exchange,提问作者ArrchanaMohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:31:24