springBoot,springCode項目 java 讀取Excel 文件操作

来源:https://www.cnblogs.com/52mqq/archive/2023/03/24/17252348.html
-Advertisement-
Play Games

導入的文件 前端點擊上傳得到文件(MultipartFile file 【這裡是存放的臨時文件】) 本人前端用的vue3,elementui, 導入按鈕代碼 <!--導入文件 --> <el-col :span="1.5"> <el-button type="info" plain icon="el ...


導入的文件

img

前端點擊上傳得到文件(MultipartFile file 【這裡是存放的臨時文件】)

  • 本人前端用的vue3,elementui,
  • 導入按鈕代碼
<!--導入文件 -->
      <el-col :span="1.5">
        <el-button type="info"
                   plain
                   icon="el-icon-upload"
                   size="mini"
                   @click="handleImport"
                   v-hasPermi="['production:monthly_production_plan:import']"
        >導入</el-button>
      </el-col>

img

  • 彈出框代碼
<!-- 月度焊接計劃導入對話框 -->
    <el-dialog :title="upload.title"
               :visible.sync="upload.open"
               width="400px"
               append-to-body
               :close-on-click-modal="false">
      <el-upload ref="upload"
                 :limit="1"
                 accept=".xlsx, .xls"
                 :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport"
                 :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess"
                 :auto-upload="false"
                 drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          將文件拖到此處,或
          <em>點擊上傳</em>
        </div>
        <div class="el-upload__tip"
             style="color:red"
             slot="tip">提示:僅允許導入“xls”或“xlsx”格式文件!</div>
      </el-upload>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="submitFileForm">確 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

img

  • js代碼 return{}層(upload參數)前端不清楚的請先看一下vue 框架官方文檔
return {
      //導入
      upload: {
        // 是否顯示彈出層(導入)
        open: false,
        // 彈出層標題(導入)
        title: "",
        // 是否禁用上傳
        isUploading: false,
        // 是否更新已經存在的數據
        updateSupport: 0,
        // 設置上傳的請求頭部
        headers: { Authorization: "Bearer " + getToken() },
        // 上傳的地址(後臺介面)
        url: process.env.VUE_APP_BASE_API + "/production/monthly_production_plan/importData"
      },
    }; 
  • js代碼 methods: {}中使用方法
methods: {
    /** 導入按鈕操作 */
    handleImport() {
      console.log(this)
      this.upload.title = "焊接月度生產計劃導入";
      this.upload.open = true;
    },
    /** 下載模板操作 */
    importTemplate() {
      this.download('production/monthly_production_plan/importTemplate', {
      }, `焊接月度生產計劃_${new Date().getTime()}.xlsx`)
    },
     // 文件上傳中處理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上傳成功處理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "導入結果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上傳文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
}

mysql數據表

drop table if exists iot_dos_welding_monthly_production_plan;
CREATE TABLE `iot_dos_welding_monthly_production_plan` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
  `planned_time` date DEFAULT NULL COMMENT '計劃時間',
  `planned_output` Double DEFAULT NULL COMMENT '計劃產量',
    `updated_by` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '更新者',
  `creation_time` datetime DEFAULT NULL COMMENT '創建時間',
    `index_id` BIGINT DEFAULT 1,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='焊接月度生產計劃';
-- DELETE FROM iot_dos_welding_monthly_production_plan;
create unique index idx_planned_time_index_id on iot_dos_welding_monthly_production_plan(planned_time, index_id);

• IotDosWeldingMonthlyProductionPlan 實體類domain

package com.sunkun.iot.production.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.core.annotation.Excel;
import com.ruoyi.common.core.web.domain.BaseEntity;
/**
 * 焊接月度生產計劃對象 iot_dos_welding_monthly_production_plan
 * 
 * @author xiaolv
 * @date 2023-02-03
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class IotDosWeldingMonthlyProductionPlan extends BaseEntity
{
    private static final long serialVersionUID = 1L;
    /** 主鍵id */
    @Excel(name = "ID")
    private Integer id;
    /** 計劃時間 */
    @JsonFormat(pattern = "yyyy-MM-dd")
    @Excel(name = "創建時間", width = 30, dateFormat = "yyyy-MM-dd")
    private Date plannedTime;
    /** 計劃產量 */
    @Excel(name = "計劃產量")
    private Double plannedOutput;
    /** 更新者 */
    @Excel(name = "更新者")
    private String updatedBy;
    /** 創建時間 */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Excel(name = "創建時間", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
    private Date creationTime;
    /** 索引值 */
    private Integer indexId;
}

後臺接收(MultipartFile file 【這裡是存放的臨時文件】)

  • controller 層介面 本人介面[/production/monthly_production_plan/importData]{根據個人需求定義自己的介面}(MultipartFile file 【這裡是存放的臨時文件】)
/**
     * 焊接月度生產計劃導入數據
     */
    @Log(title = "焊接月度生產計劃導入數據", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        String message = "";
        try {
            List<IotDosWeldingMonthlyProductionPlan> list = WeldingMonthlyProductionPlanExcelUtil.importWeldingMonthlyProductionPlan(file);
            if(list.size() > 0) {
                message = iotDosWeldingMonthlyProductionPlanService.batchProcessingDataWelding(list);
            }else {
                message="該次導入的數據集為空,請檢查導入的Excel文件!!!";
            }
        }catch (Exception e){
            e.printStackTrace();
            message="數據導入失敗。";
        }
        return AjaxResult.success(message);
    }
  • 自定義 WeldingMonthlyProductionPlanExcelUtil 用於讀取文件信息 (MultipartFile file 【這裡是存放的臨時文件】)
package com.sunkun.iot.production.utils;

import com.sunkun.iot.production.domain.IotDosWeldingMonthlyProductionPlan;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.sunkun.iot.baseinfo.utils.BomExcelUnit.getSheetByWorkbook;
import static com.sunkun.iot.baseinfo.utils.BomExcelUnit.getWorkbookByInputStream;

public class WeldingMonthlyProductionPlanExcelUtil {
    /*讀取月度焊接計劃文件信息*/
    public static List<IotDosWeldingMonthlyProductionPlan> importWeldingMonthlyProductionPlan(MultipartFile file) throws IOException {
        System.out.println("MultipartFile::"+file);
        List<IotDosWeldingMonthlyProductionPlan> list = new ArrayList<>();
        Workbook workBook = null;
        String planNum = "";
        //得到工作空間
        workBook = getWorkbookByInputStream(file.getInputStream(), file.getOriginalFilename());
        //得到工作表
        Sheet sheet = getSheetByWorkbook(workBook, 0);
        if (sheet.getRow(2000) != null){
            throw new RuntimeException("系統已限制單批次導入必須小於或等於2000筆!");
        }
        //獲取有幾個sheet 遍歷
        int numberOfSheets = workBook.getNumberOfSheets();
        System.out.println(numberOfSheets);
        //獲取第幾張表
        System.out.println("工作表名稱:" + sheet);
        int rowsOfSheet = sheet.getPhysicalNumberOfRows();
        System.out.println("當前表格的總行數:" + rowsOfSheet);
        //獲取當月天數
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        int day = Integer.parseInt(format.substring((format.lastIndexOf("-") + 1)));//得到本月天數
        //得到當月日期集
        List<String> dateList = getDayByMonth();//自定義方法得到這個月的所有年月日
        //得到導入的數據集
        for (int i = 0; i<=day;i++){
            IotDosWeldingMonthlyProductionPlan welding = new IotDosWeldingMonthlyProductionPlan();
            if(i==0){
                continue;
            }
            welding.setPlannedTime(StringToDate(dateList.get(i-1).trim()));//通過自定義方法得到時間
            welding.setCreationTime(new Date());
            if(sheet.getRow(1).getCell(i).toString().trim().equals("")){
                welding.setPlannedOutput(0.0);
            }else {
                planNum = sheet.getRow(1).getCell(i).toString().trim();
                welding.setPlannedOutput(Double.valueOf(planNum));
            }
            list.add(welding);
        }
        return list;
    }

    /**
     * 通過函數獲取當月天數
     * @return
     */
    public static List<String> getDayByMonth(){
        List<String> data = new ArrayList<>();
        try {
            Calendar c = Calendar.getInstance();
            // 獲取當前的年份
            int year = c.get(Calendar.YEAR);
            // 獲取當前的月份(需要加1才是現在的月份)
            int month = c.get(Calendar.MONTH) + 1;
            // 獲取本月的總天數
            int dayCount = c.getActualMaximum(Calendar.DAY_OF_MONTH);
            // 定義時間格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 開始日期為當前年月拼接1號
            Date startDate = sdf.parse(year + "-" + month + "-01");
            // 結束日期為當前年月拼接該月最大天數
            Date endDate = sdf.parse(year + "-" + month + "-" + dayCount);
            // 設置calendar的開始日期
            c.setTime(startDate);
            // 當前時間小於等於設定的結束時間
            while(c.getTime().compareTo(endDate) <= 0){
                String time = sdf.format(c.getTime());
                data.add(time);
                // 當前日期加1
                c.add(Calendar.DATE, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     *  String 轉 date
     * @param datetime
     * @return
     */
    public static Date StringToDate(String datetime){
        SimpleDateFormat sdFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = sdFormat.parse(datetime);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }
}
    /**
     * 月度焊接計劃批量新增
     * @param list
     * @return
     */
    int insertIotDosWeldingMonthlyProductionPlanList(List<IotDosWeldingMonthlyProductionPlan> list);

mapper.xml

<insert id="insertIotDosWeldingMonthlyProductionPlanList" parameterType="IotDosWeldingMonthlyProductionPlan">
        insert into iot_dos_welding_monthly_production_plan
        (planned_time, planned_output, updated_by, creation_time, index_id)
        VALUES
        <foreach collection ="list" item="welding" separator =",">
            (#{welding.plannedTime},#{welding.plannedOutput},#{welding.updatedBy},#{welding.creationTime},#{welding.indexId})
        </foreach >
        ON DUPLICATE KEY UPDATE 
        planned_output = VALUES(planned_output),
        updated_by = VALUES(updated_by),
        creation_time = VALUES(creation_time)
    </insert>
  • service 層和 serviceImpl層
package com.sunkun.iot.production.service;

import java.util.List;

import com.sunkun.iot.production.domain.IotDosShopCalendar;
import com.sunkun.iot.production.domain.IotDosWeldingMonthlyProductionPlan;

/**
 * 焊接月度生產計劃Service介面
 * 
 * @author xiaolv
 * @date 2023-02-03
 */
public interface IIotDosWeldingMonthlyProductionPlanService 
{
    /**
     * 批量新增
     * @param list
     * @return
     */
    int insertIotDosWeldingMonthlyProductionPlanList(List<IotDosWeldingMonthlyProductionPlan> list);

    /**
     * 批量處理數據
     * @param list
     * @return
     */
    String batchProcessingDataWelding(List<IotDosWeldingMonthlyProductionPlan> list);
}
package com.sunkun.iot.production.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.sunkun.iot.production.mapper.IotDosShopCalendarMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sunkun.iot.production.mapper.IotDosWeldingMonthlyProductionPlanMapper;
import com.sunkun.iot.production.domain.IotDosWeldingMonthlyProductionPlan;
import com.sunkun.iot.production.service.IIotDosWeldingMonthlyProductionPlanService;

import javax.validation.Validator;

/**
 * 焊接月度生產計劃Service業務層處理
 * 
 * @author xiaolv
 * @date 2023-02-03
 */
@Service
public class IotDosWeldingMonthlyProductionPlanServiceImpl implements IIotDosWeldingMonthlyProductionPlanService 
{

    private static final Logger log = LoggerFactory.getLogger(IotDosShopCalendarMapper.class);
    @Autowired
    private IotDosWeldingMonthlyProductionPlanMapper iotDosWeldingMonthlyProductionPlanMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private TokenService tokenService;
  

    /**
     * 月度焊接計劃批量新增
     *
     * @param list
     * @return
     */
    @Override
    public int insertIotDosWeldingMonthlyProductionPlanList(List<IotDosWeldingMonthlyProductionPlan> list) {
        List<IotDosWeldingMonthlyProductionPlan> weldingList = new ArrayList<>();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String user = loginUser.getUsername();
        for (IotDosWeldingMonthlyProductionPlan plan : list) {
            IotDosWeldingMonthlyProductionPlan welding = new IotDosWeldingMonthlyProductionPlan();
            welding.setId(plan.getId());
            welding.setPlannedTime(plan.getPlannedTime());
            welding.setPlannedOutput(plan.getPlannedOutput());
            welding.setUpdatedBy(user);
            welding.setCreationTime(plan.getCreationTime());
            welding.setIndexId(1);
            weldingList.add(welding);
        }
        int count = iotDosWeldingMonthlyProductionPlanMapper.insertIotDosWeldingMonthlyProductionPlanList(weldingList);
        return count;
    }

    @Override
    public String batchProcessingDataWelding(List<IotDosWeldingMonthlyProductionPlan> list) {
        int num = insertIotDosWeldingMonthlyProductionPlanList(list);
        return "導入焊接月度計劃總數據條數:"+list.size();
    }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • SpringBoot資料庫操作 1.JDBC+HikariDataSource 在SpringBoot 2.x項目中,預設使用Hikari連接池管理數據源。相比於傳統的 C3P0 、DBCP、Tomcat jdbc 等連接池更加優秀。 當項目pom.xml引入spring-boot-starter- ...
  • 一個新應用 房地產廣告模塊 假設需要開發一個房地產模塊,該模塊覆蓋未包含在標準模塊集中特定業務領域。 以下為包含一些廣告的主列表視圖 form視圖頂層區域概括了房產的重要信息,比如name,Property Type, Postcode等等。 列表記錄詳情頁中,第一個tab包含了房產的描述信息,比如 ...
  • 生產者消費者問題 簡介 生產者消費者模式並不是GOF提出的23種設計模式之一,23種設計模式都是建立在面向對象的基礎之上的,但其實面向過程的編程中也有很多高效的編程模式,生產者消費者模式便是其中之一,它是我們編程過程中最常用的一種設計模式。 在實際的軟體開發過程中,經常會碰到如下場景:某個模塊負責產 ...
  • 之前用過NXOpen PDM的命名空間下的類,現在記錄一下通過PDM命名空間下的類查詢Teamcenter零組件的信息,也可以用來判斷該零組件是否存在。 1-該工程為DLL工程,直接在NX界面調用,所以直接獲取NXSession。 2-查詢函數advanced用到的查詢為:__NX_STD_ANY_ ...
  • 本文已收錄至Github,推薦閱讀 👉 Java隨想錄 微信公眾號:Java隨想錄 摘要 Redis是一款性能強勁的記憶體資料庫,但是在使用過程中,我們可能會遇到Big Key問題,這個問題就是Redis中某個key的value過大,所以Big Key問題本質是Big Value問題,導致Redis ...
  • 9 月 15 日,Figma 的 CEO Dylan Field 發佈消息:今天,Figma 宣佈接受 Adobe 的收購... Adobe 以約 200 億美元收購 Figma,這也是 Adobe 該公司在其歷史上的最大一筆收購。那是什麼樣的魔力,讓 Figma 被 Adobe 收購呢?下麵以定位 ...
  • 實現Redis的database層(核心層:處理命令並返回) https://github.com/csgopher/go-redis 本文涉及以下文件: dict:定義字典的一些方法 sync_dict:實現dict db:分資料庫 command:定義指令 ping,keys,string:指令 ...
  • Antlr4 簡介 ANTLR(全名:ANother Tool for Language Recognition)是基於LL(*)演算法實現的語法解析器生成器(parser generator),用Java語言編寫,使用自上而下(top-down)的遞歸下降LL剖析器方法。由舊金山大學的Terence ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...