欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot實現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并保存到本地

 更新時間:2022年09月27日 11:23:55   作者:天海奈奈  
這篇文章主要為大家詳細(xì)介紹了Springboot實現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并將文件保存到本地效果的方法,文中的示例代講解詳細(xì),需要的可以參考一下

前言

當(dāng)我們給數(shù)據(jù)庫中的表中添加數(shù)據(jù)時一般都是進(jìn)入圖形化界面進(jìn)行手動添加,或者進(jìn)直接導(dǎo)入現(xiàn)成的sql文件,但是有的時候我們會需要去導(dǎo)入大量的數(shù)據(jù),這個時候我們不論是使用寫好的接口還是去圖形化界面添加都是十分費時費力的,這個時候使用Excel讀取表格數(shù)據(jù)并進(jìn)行導(dǎo)入就十分有必要了。本篇更著重于單個功能的開發(fā),不會從頭構(gòu)建一個項目。

成果展示

只是為了證明功能正常運行所以并沒有加太多

了解Excel表格基本屬性

workbook :一整個表格文件  

一個文件中有多個sheet

row 是 行

cell是一個單元格

這是打開了一個表跟文件,可以看出是可以有多個Sheet的,知道這幾點也就夠用了

表設(shè)計

這里使用的是我之前的用戶表。

字段比較多我們只取關(guān)注2~4 也就是用戶名,密碼,個性簽名.id是自增的我們導(dǎo)入數(shù)據(jù)也不會去有用戶id這一項。這三個都是varchar類型,一會兒傳入時轉(zhuǎn)成String類型就行,如果是int的話我們需要先轉(zhuǎn)成Double再使用intValue即可。

引入依賴 

<!--        表格處理-->
        <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 class ExcelUtil {
    public static  Object getCellValue(Cell cell){
        switch (cell.getCellTypeEnum()){
            //字符串
            case STRING:
                return cell.getStringCellValue();
            //布爾
            case BOOLEAN:
                return cell.getBooleanCellValue();
            //數(shù)值
            case NUMERIC:
                return cell.getNumericCellValue();
        }
        return null;
    }
}

Controller

 @PostMapping("/send/upload")
    @ResponseBody
    public ApiRestResponse uploadUser(@RequestParam("file")MultipartFile multipartFile) throws IOException {
                //獲取文件名
                String fileName = multipartFile.getOriginalFilename();
                String fixName = fileName.substring(fileName.lastIndexOf("."));
                //生成唯一UUID
                UUID uuid = UUID.randomUUID();
                String newFileName = uuid.toString() + fixName;
                //創(chuàng)建文件
                File file = new File(Constant.FILE_UPLOAD_DIR);
                File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
                if(!file.exists()){
                    if(!file.mkdir()){
                        throw new XatuMallException(0000000,"文件創(chuàng)建失敗");
                    }
                }
                try {
                    multipartFile.transferTo(destFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                userService.addUserList(destFile);
                return ApiRestResponse.success();
    }

這里注意,我們這個文件地址是需要配置的,并不是寫一個路徑就行。參考:Springboot實現(xiàn)圖片上傳功能的示例代碼

配置方法這里有說,但是要記得還要在appli那個配置文件里加一行 

file.upload.dir=D:/pictures/ 每個人不一樣,但是這與你contant類里的地址是綁定的

entity

public class User {
    private Integer id;
 
    private String username;
 
    private String password;
 
    private String personalizedSignature;
 
    private Integer role;
 
    private Date createTime;
 
    private Date updateTime;
 
    private String emailAddress;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
 
    public String getPersonalizedSignature() {
        return personalizedSignature;
    }
 
    public void setPersonalizedSignature(String personalizedSignature) {
        this.personalizedSignature = personalizedSignature == null ? null : personalizedSignature.trim();
    }
 
    public Integer getRole() {
        return role;
    }
 
    public void setRole(Integer role) {
        this.role = role;
    }
 
    public Date getCreateTime() {
        return createTime;
    }
 
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
 
    public Date getUpdateTime() {
        return updateTime;
    }
 
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
 
    public String getEmailAddress() {
        return emailAddress;
    }
 
    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress == null ? null : emailAddress.trim();
    }
}

Mapper

public interface UserMapper {
 
    User selectByName(String username);
 
}

xml

  <select id="selectByName" parameterType="java.lang.String" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"></include>
    from xatu_mall_user
    where username = #{username,jdbcType=VARCHAR}
  </select>

理解原理就好,不要去糾結(jié)表名。

UserService

Imp

 @Override
    public void addUserList(File destFile) throws IOException {
        List<User> users = readUsersFromExcel(destFile);
        for (int i = 0; i < users.size(); i++){
            User user = users.get(i);
            User userOld = userMapper.selectByName(user.getUsername());
            if(userOld != null){
                System.out.println("重名");
            }
            int count = userMapper.insertSelective(user);
            if(count == 0){
                System.out.println("添加失敗");
            }
        }
 
    }
    private List<User> readUsersFromExcel(File excelFile) throws IOException {
        ArrayList<User> listUser =new ArrayList<>();
        FileInputStream fileInputStream = new FileInputStream(excelFile);
 
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
        XSSFSheet firstSheet = xssfWorkbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();
        while(iterator.hasNext()){
            org.apache.poi.ss.usermodel.Row nextRow = iterator.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();
            User aUser = new User();
 
            while(cellIterator.hasNext()){
                Cell nextCell = cellIterator.next();
                int columnIndex = nextCell.getColumnIndex();
                switch (columnIndex){
                    case 0:
                        aUser.setUsername((String) ExcelUtil.getCellValue(nextCell));
                        break;
                    case 1:
                        aUser.setPassword((String) ExcelUtil.getCellValue(nextCell));
                        break;
                    case 2:
                        aUser.setPersonalizedSignature((String) ExcelUtil.getCellValue(nextCell));
                        break;
 
 
                }
            }
            listUser.add(aUser);
        }
        xssfWorkbook.close();
        fileInputStream.close();
        return listUser;
 
    }

重名那里偷懶了,按理說應(yīng)該拋出異常的。

void addUserList(File destFile) throws IOException;

測試

打開postman  這里需要注意的地方是我們是postMapping 并且

選擇的是Body 和form-data 

后面就能去選擇我么要讀取的表格文件了,但是我們讀取的是xlsx xls是不能讀的,你改后綴也是不行的,要建立時就是xlsx。

總結(jié)

這個技術(shù)也是很實用的技術(shù),讓我們可以很便捷的快速從表格中讀取數(shù)據(jù)并將數(shù)據(jù)上傳。文件保存到本地可以去看放的鏈接,實際上與上傳圖片是一樣的。

以上就是Springboot實現(xiàn)Excel批量導(dǎo)入數(shù)據(jù)并保存到本地的詳細(xì)內(nèi)容,更多關(guān)于Springboot Excel批量導(dǎo)入數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論