草庐IT

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

秋子渊 2023-03-28 原文

导入的文件

前端点击上传得到文件(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>

  • 弹出框代码
<!-- 月度焊接计划导入对话框 -->
    <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>

  • 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();
    }
}

有关springBoot,springCode项目 java 读取Excel 文件操作的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  8. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  9. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  10. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

随机推荐