springBoot,springCode项目 java 读取Excel 文件操作

打印 上一主题 下一主题

主题 580|帖子 580|积分 1740

导入的文件

前端点击上传得到文件(MultipartFile file 【这里是存放的临时文件】)


  • 本人前端用的vue3,elementui,
  • 导入按钮代码
  1.       <el-col :span="1.5">
  2.         <el-button type="info"
  3.                    plain
  4.                    icon="el-icon-upload"
  5.                    size="mini"
  6.                    @click="handleImport"
  7.                    v-hasPermi="['production:monthly_production_plan:import']"
  8.         >导入</el-button>
  9.       </el-col>
复制代码


  • 弹出框代码
  1.     <el-dialog :title="upload.title"
  2.                :visible.sync="upload.open"
  3.                width="400px"
  4.                append-to-body
  5.                :close-on-click-modal="false">
  6.       <el-upload ref="upload"
  7.                  :limit="1"
  8.                  accept=".xlsx, .xls"
  9.                  :headers="upload.headers"
  10.                  :action="upload.url + '?updateSupport=' + upload.updateSupport"
  11.                  :disabled="upload.isUploading"
  12.                  :on-progress="handleFileUploadProgress"
  13.                  :on-success="handleFileSuccess"
  14.                  :auto-upload="false"
  15.                  drag>
  16.         <i ></i>
  17.         
  18.           将文件拖到此处,或
  19.           <em>点击上传</em>
  20.         
  21.         提示:仅允许导入“xls”或“xlsx”格式文件!
  22.       </el-upload>
  23.       
  24.         <el-button type="primary"
  25.                    @click="submitFileForm">确 定</el-button>
  26.         <el-button @click="upload.open = false">取 消</el-button>
  27.       
  28.     </el-dialog>
复制代码


  • js代码 return{}层(upload参数)前端不清楚的请先看一下vue 框架官方文档
  1. return {
  2.       //导入
  3.       upload: {
  4.         // 是否显示弹出层(导入)
  5.         open: false,
  6.         // 弹出层标题(导入)
  7.         title: "",
  8.         // 是否禁用上传
  9.         isUploading: false,
  10.         // 是否更新已经存在的数据
  11.         updateSupport: 0,
  12.         // 设置上传的请求头部
  13.         headers: { Authorization: "Bearer " + getToken() },
  14.         // 上传的地址(后台接口)
  15.         url: process.env.VUE_APP_BASE_API + "/production/monthly_production_plan/importData"
  16.       },
  17.     };
复制代码

  • js代码  methods: {}中使用方法
  1. methods: {
  2.     /** 导入按钮操作 */
  3.     handleImport() {
  4.       console.log(this)
  5.       this.upload.title = "焊接月度生产计划导入";
  6.       this.upload.open = true;
  7.     },
  8.     /** 下载模板操作 */
  9.     importTemplate() {
  10.       this.download('production/monthly_production_plan/importTemplate', {
  11.       }, `焊接月度生产计划_${new Date().getTime()}.xlsx`)
  12.     },
  13.      // 文件上传中处理
  14.     handleFileUploadProgress(event, file, fileList) {
  15.       this.upload.isUploading = true;
  16.     },
  17.     // 文件上传成功处理
  18.     handleFileSuccess(response, file, fileList) {
  19.       this.upload.open = false;
  20.       this.upload.isUploading = false;
  21.       this.$refs.upload.clearFiles();
  22.       this.$alert("" + response.msg + "", "导入结果", { dangerouslyUseHTMLString: true });
  23.       this.getList();
  24.     },
  25.     // 提交上传文件
  26.     submitFileForm() {
  27.       this.$refs.upload.submit();
  28.     }
  29. }
复制代码
mysql数据表
  1. drop table if exists iot_dos_welding_monthly_production_plan;
  2. CREATE TABLE `iot_dos_welding_monthly_production_plan` (
  3.   `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id',
  4.   `planned_time` date DEFAULT NULL COMMENT '计划时间',
  5.   `planned_output` Double DEFAULT NULL COMMENT '计划产量',
  6.     `updated_by` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '更新者',
  7.   `creation_time` datetime DEFAULT NULL COMMENT '创建时间',
  8.     `index_id` BIGINT DEFAULT 1,
  9.   PRIMARY KEY (`id`) USING BTREE
  10. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='焊接月度生产计划';
  11. -- DELETE FROM iot_dos_welding_monthly_production_plan;
  12. create unique index idx_planned_time_index_id on iot_dos_welding_monthly_production_plan(planned_time, index_id);
复制代码
• IotDosWeldingMonthlyProductionPlan 实体类domain
  1. package com.sunkun.iot.production.domain;
  2. import java.util.Date;
  3. import com.fasterxml.jackson.annotation.JsonFormat;
  4. import io.swagger.models.auth.In;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Builder;
  7. import lombok.Data;
  8. import lombok.NoArgsConstructor;
  9. import org.apache.commons.lang3.builder.ToStringBuilder;
  10. import org.apache.commons.lang3.builder.ToStringStyle;
  11. import com.ruoyi.common.core.annotation.Excel;
  12. import com.ruoyi.common.core.web.domain.BaseEntity;
  13. /**
  14. * 焊接月度生产计划对象 iot_dos_welding_monthly_production_plan
  15. *
  16. * @author xiaolv
  17. * @date 2023-02-03
  18. */
  19. @Data
  20. @Builder
  21. @AllArgsConstructor
  22. @NoArgsConstructor
  23. public class IotDosWeldingMonthlyProductionPlan extends BaseEntity
  24. {
  25.     private static final long serialVersionUID = 1L;
  26.     /** 主键id */
  27.     @Excel(name = "ID")
  28.     private Integer id;
  29.     /** 计划时间 */
  30.     @JsonFormat(pattern = "yyyy-MM-dd")
  31.     @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
  32.     private Date plannedTime;
  33.     /** 计划产量 */
  34.     @Excel(name = "计划产量")
  35.     private Double plannedOutput;
  36.     /** 更新者 */
  37.     @Excel(name = "更新者")
  38.     private String updatedBy;
  39.     /** 创建时间 */
  40.     @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  41.     @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss")
  42.     private Date creationTime;
  43.     /** 索引值 */
  44.     private Integer indexId;
  45. }
复制代码
后台接收(MultipartFile file 【这里是存放的临时文件】)


  • controller 层接口 本人接口[/production/monthly_production_plan/importData]{根据个人需求定义自己的接口}(MultipartFile file 【这里是存放的临时文件】)
  1. /**
  2.      * 焊接月度生产计划导入数据
  3.      */
  4.     @Log(title = "焊接月度生产计划导入数据", businessType = BusinessType.IMPORT)
  5.     @PostMapping("/importData")
  6.     public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
  7.     {
  8.         String message = "";
  9.         try {
  10.             List<IotDosWeldingMonthlyProductionPlan> list = WeldingMonthlyProductionPlanExcelUtil.importWeldingMonthlyProductionPlan(file);
  11.             if(list.size() > 0) {
  12.                 message = iotDosWeldingMonthlyProductionPlanService.batchProcessingDataWelding(list);
  13.             }else {
  14.                 message="该次导入的数据集为空,请检查导入的Excel文件!!!";
  15.             }
  16.         }catch (Exception e){
  17.             e.printStackTrace();
  18.             message="数据导入失败。";
  19.         }
  20.         return AjaxResult.success(message);
  21.     }
复制代码

  • 自定义 WeldingMonthlyProductionPlanExcelUtil 用于读取文件信息 (MultipartFile file 【这里是存放的临时文件】)
[code]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 importWeldingMonthlyProductionPlan(MultipartFile file) throws IOException {        System.out.println("MultipartFile::"+file);        List 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 dateList = getDayByMonth();//自定义方法得到这个月的所有年月日        //得到导入的数据集        for (int i = 0; i

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

数据人与超自然意识

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表