[详细步骤]Java将Excel文件导入到数据库表中、并使用postman测试

这篇具有很好参考价值的文章主要介绍了[详细步骤]Java将Excel文件导入到数据库表中、并使用postman测试。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、Maven依赖添加

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

2、需要使用的类

controller:ExcelController

entity:ExcelEntity(设计此实体类,需要与excel文件一一对应)

mapper:ExcelMapper

service:ExcelServiceImpl、ExcelService

util:ReadExcelUtil

3、代码

package com.dbm.exceltodatabase.controller;

import com.dbm.exceltodatabase.entity.ExcelEntity;
import com.dbm.exceltodatabase.service.ExcelService;
import com.dbm.exceltodatabase.util.ReadExcelUtil;
import com.jgdf.core.filter.http.DisableEncryptResponse;
import com.jgdf.core.web.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zhangyj
 * @create 2023/4/6
 */
@RestController
@RequestMapping("/excel")
@Api(tags = "Excel导入数据库接口")
public class ExcelController {
    @Autowired
    private ExcelService excelService;

    @PostMapping("/excelExport")
    @ApiOperation("Excel表导入数据库")
    @DisableEncryptResponse
    public R<Void> test(@RequestParam("file") MultipartFile file) {
        long startTime = System.currentTimeMillis();
        Map<String, Object> res = new HashMap<>();
        List<ExcelEntity> excelInfo = ReadExcelUtil.getExcelInfo(file);
        for (ExcelEntity patientInfo : excelInfo) {
            excelService.save(patientInfo);
        }
        long endTime = System.currentTimeMillis();
        String time = String.valueOf((endTime - startTime) / 1000);
        res.put("time", "导入数据用时:" + time + "秒");
//        renderResult(response, res);
        System.out.println(res);
        return R.ok();
    }

    @PostMapping("/select")
    @ApiOperation("查询数据库表详情")
    @DisableEncryptResponse
    public R<List<ExcelEntity>> select() {
        List<ExcelEntity> list = excelService.select();
        return R.ok(list);
    }

}
package com.dbm.exceltodatabase.entity;

import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;

/**
 * @author Zhangyj
 * @create 2023/4/6
 */
@TableName(value = "excel")
public class ExcelEntity {
    @ApiModelProperty("序号")
    @TableField("f_id")
    @ExcelProperty("序号")
    private String id;

    @ApiModelProperty("区域")
    @TableField("f_area")
    @ExcelProperty("区域")
    private String area;

    @ApiModelProperty("站址名称")
    @TableField("f_site_name")
    @ExcelProperty("站址名称")
    private String siteName;

    @ApiModelProperty("塔型")
    @TableField("f_tower_type")
    @ExcelProperty("塔型")
    private String towerType;

    @ApiModelProperty("站址经度")
    @TableField("f_site_longitude")
    @ExcelProperty("站址经度")
    private String siteLongitude;

    @ApiModelProperty("站址维度")
    @TableField("f_site_dimension")
    @ExcelProperty("站址维度")
    private String siteDimension;

    @ApiModelProperty("方位角度")
    @TableField("f_position_angle")
    @ExcelProperty("方位角度")
    private String positionAngle;

    @ApiModelProperty("详细位置")
    @TableField("f_detail_location")
    @ExcelProperty("详细位置")
    private String detailLocation;

    @ApiModelProperty("云台编号")
    @TableField("f_yuntai_number")
    @ExcelProperty("云台编号")
    private String yuntaiNumber;

    @ApiModelProperty("设备编号")
    @TableField("f_equipment_number")
    @ExcelProperty("设备编号")
    private String equipmentNumber;

    @ApiModelProperty("运营商")
    @TableField("f_operator")
    @ExcelProperty("运营商")
    private String operator;

    @ApiModelProperty("ip地址")
    @TableField("f_ip_address")
    @ExcelProperty("ip地址")
    private String ipAddress;

    public ExcelEntity(String id, String area, String siteName, String towerType, String siteLongitude, String siteDimension, String positionAngle, String detailLocation, String yuntaiNumber, String equipmentNumber, String operator, String ipAddress) {
        this.id = id;
        this.area = area;
        this.siteName = siteName;
        this.towerType = towerType;
        this.siteLongitude = siteLongitude;
        this.siteDimension = siteDimension;
        this.positionAngle = positionAngle;
        this.detailLocation = detailLocation;
        this.yuntaiNumber = yuntaiNumber;
        this.equipmentNumber = equipmentNumber;
        this.operator = operator;
        this.ipAddress = ipAddress;
    }

    public ExcelEntity() {

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getSiteName() {
        return siteName;
    }

    public void setSiteName(String siteName) {
        this.siteName = siteName;
    }

    public String getTowerType() {
        return towerType;
    }

    public void setTowerType(String towerType) {
        this.towerType = towerType;
    }

    public String getSiteLongitude() {
        return siteLongitude;
    }

    public void setSiteLongitude(String siteLongitude) {
        this.siteLongitude = siteLongitude;
    }

    public String getSiteDimension() {
        return siteDimension;
    }

    public void setSiteDimension(String siteDimension) {
        this.siteDimension = siteDimension;
    }

    public String getPositionAngle() {
        return positionAngle;
    }

    public void setPositionAngle(String positionAngle) {
        this.positionAngle = positionAngle;
    }

    public String getDetailLocation() {
        return detailLocation;
    }

    public void setDetailLocation(String detailLocation) {
        this.detailLocation = detailLocation;
    }

    public String getYuntaiNumber() {
        return yuntaiNumber;
    }

    public void setYuntaiNumber(String yuntaiNumber) {
        this.yuntaiNumber = yuntaiNumber;
    }

    public String getEquipmentNumber() {
        return equipmentNumber;
    }

    public void setEquipmentNumber(String equipmentNumber) {
        this.equipmentNumber = equipmentNumber;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    @Override
    public String toString() {
        return "ExcelEntity{" +
                "id='" + id + '\'' +
                ", area='" + area + '\'' +
                ", siteName='" + siteName + '\'' +
                ", towerType='" + towerType + '\'' +
                ", siteLongitude='" + siteLongitude + '\'' +
                ", siteDimension='" + siteDimension + '\'' +
                ", positionAngle='" + positionAngle + '\'' +
                ", detailLocation='" + detailLocation + '\'' +
                ", yuntaiNumber='" + yuntaiNumber + '\'' +
                ", equipmentNumber='" + equipmentNumber + '\'' +
                ", operator='" + operator + '\'' +
                ", ipAddress='" + ipAddress + '\'' +
                '}';
    }
}
package com.dbm.exceltodatabase.mapper;

import com.dbm.exceltodatabase.entity.ExcelEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Zhangyj
 * @create 2023/4/6
 */
@Mapper
@Repository
public interface ExcelMapper {
    //Excel表导入数据库
    @Insert("insert into excel(f_id,f_area,f_site_name,f_tower_type,f_site_longitude," +
            "f_site_dimension,f_position_angle,f_detail_location,f_yuntai_number,f_equipment_number," +
            "f_operator,f_ip_address)" +
            " values(#{id},#{area},#{siteName},#{towerType},#{siteLongitude}," +
            "#{siteDimension},#{positionAngle},#{detailLocation},#{yuntaiNumber},#{equipmentNumber}," +
            "#{operator},#{ipAddress})")
    int save(ExcelEntity excelEntity);

    //查询数据库表详情
    @Select("select f_id as id,f_area as area,f_site_name as siteName,f_tower_type as towerType,f_site_longitude as siteLongitude," +
            "f_site_dimension as siteDimension,f_position_angle as positionAngle,f_detail_location as detailLocation," +
            "f_yuntai_number as yuntaiNumber,f_equipment_number as equipmentNumber," +
            "f_operator as operator,f_ip_address as ipAddress " +
            "from excel")
    List<ExcelEntity> select();
}
package com.dbm.exceltodatabase.service.impl;

import com.dbm.exceltodatabase.entity.ExcelEntity;
import com.dbm.exceltodatabase.mapper.ExcelMapper;
import com.dbm.exceltodatabase.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Zhangyj
 * @create 2023/4/6
 */
@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    private ExcelMapper excelMapper;

    //Excel表导入数据库
    @Override
    public void save(ExcelEntity excelEntity) {
        excelMapper.save(excelEntity);
    }

    //查询数据库表详情
    @Override
    public List<ExcelEntity> select() {
        List<ExcelEntity> list = excelMapper.select();
        return list;
    }
}
package com.dbm.exceltodatabase.service;

import com.dbm.exceltodatabase.entity.ExcelEntity;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Zhangyj
 * @create 2023/4/6
 */
@Transactional
public interface ExcelService {
    //Excel表导入数据库
    void save(ExcelEntity excelEntity);

    //查询数据库表详情
    List<ExcelEntity> select();
}
package com.dbm.exceltodatabase.util;

import com.dbm.exceltodatabase.entity.ExcelEntity;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhangyj
 * @create 2023/4/6
 */
public class ReadExcelUtil {
    //总行数
    private static int totalRows = 0;
    //总条数
    private static int totalCells = 0;
    //错误信息接收器
    private static String errorMsg;

    /**
     * 读EXCEL文件,获取信息集合
     *
     * @return
     */
    public static List<ExcelEntity> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();//获取文件名
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            //file.getinputstream()的作用是获取文件的输入流,可以用来读取文件的内容。
            List<ExcelEntity> userList = createExcel(mFile.getInputStream(), isExcel2003);
            return userList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据excel里面的内容读取客户信息
     *
     * @param is          输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public static List<ExcelEntity> createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            List<ExcelEntity> userList = readExcelValue(wb);// 读取Excel里面客户的信息
            return userList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取Excel里面客户的信息
     *
     * @param wb
     * @return
     */
    private static List<ExcelEntity> readExcelValue(Workbook wb) {
        //默认会跳过第一行标题
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<ExcelEntity> userList = new ArrayList<ExcelEntity>();
        // 循环Excel行数
        for (int r = 2; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            ExcelEntity user = new ExcelEntity();
            // 循环Excel的列
            for (int c = 0; c < totalCells + 1; c++) {
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (c == 0) {           //第一列
                        //如果是纯数字,将单元格类型转为String
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setId(cell.getStringCellValue());//将单元格数据赋值给user
                    } else if (c == 1) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setArea(cell.getStringCellValue());
                    } else if (c == 2) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        String stringCellValue = cell.getStringCellValue();
                        user.setSiteName(stringCellValue);
                    } else if (c == 3) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setTowerType(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 4) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setSiteLongitude(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 5) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setSiteDimension(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 6) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setPositionAngle(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 7) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setDetailLocation(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 8) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setYuntaiNumber(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 9) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setEquipmentNumber(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 10) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setOperator(String.valueOf(cell.getStringCellValue()));
                    } else if (c == 11) {
                        if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                            cell.setCellType(CellType.STRING);
                        }
                        user.setIpAddress(String.valueOf(cell.getStringCellValue()));
                    }
                }
            }

            // 添加到list
            userList.add(user);
        }
        return userList;
    }

    /**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

}

4、postman测试

postman怎么测试导入excel文件,java,数据库,excel

file(excel)的文件路径需真实存在,下图进行设置路径、我的excel放在了D:\excel

如果不行设置或路径不存在、会出现以下提示

This file isn't in your working directory. Teammates you share this request with won't be able to use this file. To make collaboration easier you can setup your working directory in Settings.

 postman怎么测试导入excel文件,java,数据库,excelpostman怎么测试导入excel文件,java,数据库,excel

postman怎么测试导入excel文件,java,数据库,excel

 文章来源地址https://www.toymoban.com/news/detail-734060.html

 

 

到了这里,关于[详细步骤]Java将Excel文件导入到数据库表中、并使用postman测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口

    最近由于学校压力,心情不太好,没咋写博客; 但最近做数据库实验的时候,数据是xlsx文件展示的,要求将这些导入数据库,我懒得去下载MySQL WorkBench等等可视化的工具,就想着写个程序来实现这个功能~ 只要访问这个接口,输入xlsx表格文件的路径,就会向程序设置好的数

    2024年02月07日
    浏览(39)
  • 【JDBC篇】java 如何连接数据库(超详细步骤)

    本文以java连接mysql为例讲解;仅仅记录了一部分知识点,其余我还没学完,后面会补充!初学JDBC文章仅仅是我个人对知识点的理解,请谨慎参考! 目录 Java连接数据库前期工作: JDBC程序编写步骤总览  JDBC编程的六步: 1,注册驱动   2,获得连接   3,获得数据库操作对象

    2024年02月08日
    浏览(51)
  • Java解析Excel文件并把数据存入数据库

    使用SpingMVC和hibernate框架实现 web.xml中的配置文件就按照这种方式写,只需要把\\\"application.xml\\\"换成你的配置文件名即可 在这个配置文件中你还可以规定上传文件的格式以及大小等多种属性限制 注意: 1.enctype=“multipart/form-data” 必须写,封装表单 2.method=“post”,提交方式必须

    2024年01月23日
    浏览(36)
  • 【数据库】将excel数据导入mysql数据库

    环境:Windows10 mysql8以上 将你要导入的excel表另存为txt格式 打开txt格式文件,删除表头行并另存为并更改编码方式(由于与数据库的编码不同,会导致导入报错)   通过命令行登录数据库 win+r cmd进入  进入装mysql的目录位置(进入到bin目录)  输入命令进入数据库,注意由于

    2024年02月14日
    浏览(41)
  • 数据库——多种方法导入Excel数据

    接下来就一直点击NEXT,直到完成 此时EXCEL的数据就被导入进SQL Server了: 这个技巧就是直接使用复制粘贴的方式: 注意:这种方法只适用于添加少量数据,如果是 几十万行 的数据,是无法这样导入的。 如图,我们在Excel当中直接复制数据: 右键PTYPES表,选择编辑前2002行:

    2024年02月04日
    浏览(65)
  • thinkadmin上传excel导入数据库

    2024年01月23日
    浏览(44)
  • Python导入Excel数据到MySQL数据库

    目录 一、所需库和模块 二、读取Excel文件并转换为pandas数据帧 三、建立与MySQL数据库的连接 四、将数据从pandas数据帧导入到MySQL数据库 五、示例代码 总结 在数据分析和处理过程中,将Excel文件导入到MySQL数据库是一种常见的需求。Excel是一种广泛使用的电子表格格式,可用于

    2024年01月17日
    浏览(39)
  • 将Excel表中数据导入MySQL数据库

     字段信息与表格对应建表:  完成。

    2024年02月07日
    浏览(39)
  • sheetJS实现把excel导入数据库

            最近在做报表导入数据库的需求,报表文件为excel里面有多个sheet。 使用FileReader异步读取上传的文件。 使用sheet.js进行excel表格内容的解析。 使用bootstrap.js的tab组件对上传的表格进行一个页面预览的展示。         ImportReportForm.asp ImportReport.asp         先选择

    2024年02月09日
    浏览(34)
  • 将excel数据导入到SQL server数据库

    将要导入的excel表格数据如下,第一行数据默认为数据库表中的字段,所以这个必须要有,否则无法映射导入。 选择你要导入数据的数据库,右键选择任务,再点击导入文件 点击下一步 选择Microsoft Excel 点击预览选择你要导入的表,选择对应版本,但是一般导入就会预设好,

    2024年02月06日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包